| 1 | //! Implementation of the `unevaluatedProperties` keyword. |
| 2 | //! |
| 3 | //! This keyword validates properties that were not evaluated by other keywords like |
| 4 | //! `properties`, `additionalProperties`, `patternProperties`, or nested schemas in |
| 5 | //! combinators (`allOf`, `anyOf`, `oneOf`), conditionals, and references. |
| 6 | //! |
| 7 | //! The implementation eagerly compiles a recursive `PropertyValidators` structure during |
| 8 | //! schema compilation, using `Shared<OnceLock>` for circular reference handling. |
| 9 | use ahash::AHashSet; |
| 10 | use fancy_regex::Regex; |
| 11 | use serde_json::{Map, Value}; |
| 12 | use std::sync::OnceLock; |
| 13 | |
| 14 | use crate::{ |
| 15 | compiler, ecma, |
| 16 | evaluation::ErrorDescription, |
| 17 | node::SchemaNode, |
| 18 | paths::{LazyLocation, Location}, |
| 19 | thread::Shared, |
| 20 | validator::{EvaluationResult, Validate, ValidationContext}, |
| 21 | ValidationError, |
| 22 | }; |
| 23 | |
| 24 | use super::CompilationResult; |
| 25 | |
| 26 | /// Lazy property validators that are compiled on first access. |
| 27 | /// Used for $recursiveRef and circular references to handle cycles during compilation. |
| 28 | pub(crate) type PendingPropertyValidators = Shared<OnceLock<PropertyValidators>>; |
| 29 | |
| 30 | /// Holds compiled validators for property evaluation in unevaluatedProperties. |
| 31 | /// This structure is built during schema compilation and used during validation. |
| 32 | #[derive(Debug, Clone)] |
| 33 | pub(crate) struct PropertyValidators { |
| 34 | /// Direct property validators from "properties" keyword |
| 35 | properties: Vec<(String, SchemaNode)>, |
| 36 | /// Validator from "additionalProperties" keyword |
| 37 | additional: Option<SchemaNode>, |
| 38 | /// Pattern-based property validators from "patternProperties" keyword |
| 39 | pattern_properties: Vec<(Regex, SchemaNode)>, |
| 40 | /// Validator from "unevaluatedProperties" keyword itself |
| 41 | unevaluated: Option<SchemaNode>, |
| 42 | /// Validators from "allOf" keyword - both the schema and its property validators |
| 43 | all_of: Vec<(SchemaNode, PropertyValidators)>, |
| 44 | /// Validators from "anyOf" keyword |
| 45 | any_of: Vec<(SchemaNode, PropertyValidators)>, |
| 46 | /// Validators from "oneOf" keyword |
| 47 | one_of: Vec<(SchemaNode, PropertyValidators)>, |
| 48 | /// Conditional validators from "if/then/else" keywords |
| 49 | conditional: Option<Box<ConditionalValidators>>, |
| 50 | /// Reference validators from "$ref" keyword (may be circular) |
| 51 | ref_: Option<RefValidator>, |
| 52 | /// Reference validators from "$dynamicRef" keyword |
| 53 | dynamic_ref: Option<Box<PropertyValidators>>, |
| 54 | /// Validators from "$recursiveRef" keyword (Draft 2019-09 only) |
| 55 | /// Uses pending pattern to handle circular references |
| 56 | recursive_ref: Option<PendingPropertyValidators>, |
| 57 | /// Dependent schema validators from "dependentSchemas" keyword |
| 58 | dependent: Vec<(String, PropertyValidators)>, |
| 59 | } |
| 60 | |
| 61 | /// Reference validator - just wraps `PropertyValidators` |
| 62 | /// Circular references are handled by returning None during compilation |
| 63 | #[derive(Debug, Clone)] |
| 64 | struct RefValidator(Box<PropertyValidators>); |
| 65 | |
| 66 | /// Conditional validators from "if/then/else" keywords |
| 67 | #[derive(Debug, Clone)] |
| 68 | struct ConditionalValidators { |
| 69 | condition: SchemaNode, |
| 70 | if_: PropertyValidators, |
| 71 | then_: Option<PropertyValidators>, |
| 72 | else_: Option<PropertyValidators>, |
| 73 | } |
| 74 | |
| 75 | impl PropertyValidators { |
| 76 | /// Mark all properties that are evaluated by this schema. |
| 77 | /// This is the core logic for determining which properties should not be considered "unevaluated". |
| 78 | fn mark_evaluated_properties<'i>( |
| 79 | &self, |
| 80 | instance: &'i Value, |
| 81 | properties: &mut AHashSet<&'i String>, |
| 82 | ctx: &mut ValidationContext, |
| 83 | ) { |
| 84 | // Handle $ref first |
| 85 | if let Some(ref_) = &self.ref_ { |
| 86 | ref_.0.mark_evaluated_properties(instance, properties, ctx); |
| 87 | } |
| 88 | |
| 89 | // Handle $recursiveRef (Draft 2019-09 only) |
| 90 | // Skip if not yet initialized (circular reference) - properties will be tracked by parent |
| 91 | if let Some(recursive_ref) = &self.recursive_ref { |
| 92 | if let Some(validators) = recursive_ref.get() { |
| 93 | validators.mark_evaluated_properties(instance, properties, ctx); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | // Handle $dynamicRef (Draft 2020-12+) |
| 98 | if let Some(dynamic_ref) = &self.dynamic_ref { |
| 99 | dynamic_ref.mark_evaluated_properties(instance, properties, ctx); |
| 100 | } |
| 101 | |
| 102 | // Process properties on the instance |
| 103 | if let Value::Object(obj) = instance { |
| 104 | // Mark properties from "properties" keyword |
| 105 | for property in obj.keys() { |
| 106 | if self.properties.iter().any(|(p, _)| p == property) { |
| 107 | properties.insert(property); |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | // Check "patternProperties" keyword - mark if property name matches |
| 112 | if !self.pattern_properties.is_empty() { |
| 113 | for property in obj.keys() { |
| 114 | if properties.contains(property) { |
| 115 | continue; // Already marked by "properties" |
| 116 | } |
| 117 | for (pattern, _) in &self.pattern_properties { |
| 118 | if pattern.is_match(property).unwrap_or(false) { |
| 119 | properties.insert(property); |
| 120 | break; |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | // Check "additionalProperties" keyword - applies to properties NOT in properties/patternProperties |
| 127 | // This must be done after marking all properties/patternProperties to avoid order dependency |
| 128 | if self.additional.is_some() { |
| 129 | for property in obj.keys() { |
| 130 | // Only mark if not already marked by properties or patternProperties |
| 131 | if !properties.contains(property) { |
| 132 | properties.insert(property); |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // Check "unevaluatedProperties" keyword - marks properties that validate successfully |
| 138 | // This is crucial for nested unevaluatedProperties: a child schema's unevaluatedProperties |
| 139 | // can mark properties as evaluated for parent schemas |
| 140 | if let Some(unevaluated) = &self.unevaluated { |
| 141 | for (property, value) in obj { |
| 142 | // Skip if already marked - avoid redundant validation |
| 143 | if properties.contains(property) { |
| 144 | continue; |
| 145 | } |
| 146 | if unevaluated.is_valid(value, ctx) { |
| 147 | properties.insert(property); |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // Check "dependentSchemas" keyword |
| 153 | for (dep_property, dep_validators) in &self.dependent { |
| 154 | if obj.contains_key(dep_property) { |
| 155 | dep_validators.mark_evaluated_properties(instance, properties, ctx); |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | // Handle "if/then/else" keywords |
| 161 | if let Some(conditional) = &self.conditional { |
| 162 | conditional.mark_evaluated_properties(instance, properties, ctx); |
| 163 | } |
| 164 | |
| 165 | // Handle "allOf" keyword |
| 166 | for (node, validators) in &self.all_of { |
| 167 | if node.is_valid(instance, ctx) { |
| 168 | validators.mark_evaluated_properties(instance, properties, ctx); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // Handle "anyOf" keyword |
| 173 | for (node, validators) in &self.any_of { |
| 174 | if node.is_valid(instance, ctx) { |
| 175 | validators.mark_evaluated_properties(instance, properties, ctx); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // Handle "oneOf" keyword - only if exactly one matches |
| 180 | let one_of_matches: Vec<bool> = self |
| 181 | .one_of |
| 182 | .iter() |
| 183 | .map(|(node, _)| node.is_valid(instance, ctx)) |
| 184 | .collect(); |
| 185 | |
| 186 | if one_of_matches.iter().filter(|&&v| v).count() == 1 { |
| 187 | for ((_node, validators), &is_valid) in self.one_of.iter().zip(one_of_matches.iter()) { |
| 188 | if is_valid { |
| 189 | validators.mark_evaluated_properties(instance, properties, ctx); |
| 190 | break; |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | impl ConditionalValidators { |
| 198 | fn mark_evaluated_properties<'i>( |
| 199 | &self, |
| 200 | instance: &'i Value, |
| 201 | properties: &mut AHashSet<&'i String>, |
| 202 | ctx: &mut ValidationContext, |
| 203 | ) { |
| 204 | if self.condition.is_valid(instance, ctx) { |
| 205 | self.if_ |
| 206 | .mark_evaluated_properties(instance, properties, ctx); |
| 207 | if let Some(then_) = &self.then_ { |
| 208 | then_.mark_evaluated_properties(instance, properties, ctx); |
| 209 | } |
| 210 | } else if let Some(else_) = &self.else_ { |
| 211 | else_.mark_evaluated_properties(instance, properties, ctx); |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | /// Compile all property validators for a schema. |
| 217 | /// |
| 218 | /// Recursively builds the `PropertyValidators` tree by examining all keywords that |
| 219 | /// can evaluate properties. Handles circular references via pending nodes cached |
| 220 | /// by location and schema pointer. |
| 221 | fn compile_property_validators<'a>( |
| 222 | ctx: &compiler::Context<'_>, |
| 223 | parent: &'a Map<String, Value>, |
| 224 | ) -> Result<PropertyValidators, ValidationError<'a>> { |
| 225 | // Create a pending node and cache it before compiling to handle circular refs |
| 226 | let cache_key = ctx.location_cache_key(); |
| 227 | let pending = Shared::new(OnceLock::new()); |
| 228 | ctx.cache_pending_property_validators(cache_key.clone(), pending.clone()); |
| 229 | ctx.cache_pending_property_validators_for_schema(parent, pending.clone()); |
| 230 | |
| 231 | // Compile all parts |
| 232 | let validators = PropertyValidators { |
| 233 | properties: compile_properties(ctx, parent)?, |
| 234 | additional: compile_additional(ctx, parent)?, |
| 235 | pattern_properties: compile_pattern_properties(ctx, parent)?, |
| 236 | unevaluated: compile_unevaluated(ctx, parent)?, |
| 237 | all_of: compile_all_of(ctx, parent)?, |
| 238 | any_of: compile_any_of(ctx, parent)?, |
| 239 | one_of: compile_one_of(ctx, parent)?, |
| 240 | conditional: compile_conditional(ctx, parent)?, |
| 241 | ref_: compile_ref(ctx, parent).map_err(ValidationError::to_owned)?, |
| 242 | dynamic_ref: compile_dynamic_ref(ctx, parent).map_err(ValidationError::to_owned)?, |
| 243 | recursive_ref: compile_recursive_ref(ctx, parent)?, |
| 244 | dependent: compile_dependent(ctx, parent)?, |
| 245 | }; |
| 246 | |
| 247 | // Initialize the pending node. This should always succeed since we just created it. |
| 248 | pending |
| 249 | .set(validators.clone()) |
| 250 | .expect("pending node should not be initialized yet"); |
| 251 | |
| 252 | // Remove from pending cache |
| 253 | ctx.remove_pending_property_validators(&cache_key); |
| 254 | ctx.remove_pending_property_validators_for_schema(parent); |
| 255 | |
| 256 | Ok(validators) |
| 257 | } |
| 258 | |
| 259 | fn compile_properties<'a>( |
| 260 | ctx: &compiler::Context<'_>, |
| 261 | parent: &'a Map<String, Value>, |
| 262 | ) -> Result<Vec<(String, SchemaNode)>, ValidationError<'a>> { |
| 263 | let Some(Value::Object(map)) = parent.get("properties") else { |
| 264 | return Ok(Vec::new()); |
| 265 | }; |
| 266 | |
| 267 | let properties_ctx = ctx.new_at_location("properties"); |
| 268 | let mut result = Vec::with_capacity(map.len()); |
| 269 | |
| 270 | for (property, subschema) in map { |
| 271 | let prop_ctx = properties_ctx.new_at_location(property.as_str()); |
| 272 | let node = compiler::compile(&prop_ctx, prop_ctx.as_resource_ref(subschema)) |
| 273 | .map_err(ValidationError::to_owned)?; |
| 274 | result.push((property.clone(), node)); |
| 275 | } |
| 276 | |
| 277 | Ok(result) |
| 278 | } |
| 279 | |
| 280 | fn compile_additional<'a>( |
| 281 | ctx: &compiler::Context<'_>, |
| 282 | parent: &'a Map<String, Value>, |
| 283 | ) -> Result<Option<SchemaNode>, ValidationError<'a>> { |
| 284 | let Some(subschema) = parent.get("additionalProperties") else { |
| 285 | return Ok(None); |
| 286 | }; |
| 287 | |
| 288 | let additional_ctx = ctx.new_at_location("additionalProperties"); |
| 289 | let node = compiler::compile(&additional_ctx, additional_ctx.as_resource_ref(subschema)) |
| 290 | .map_err(ValidationError::to_owned)?; |
| 291 | Ok(Some(node)) |
| 292 | } |
| 293 | |
| 294 | fn compile_pattern_properties<'a>( |
| 295 | ctx: &compiler::Context<'_>, |
| 296 | parent: &'a Map<String, Value>, |
| 297 | ) -> Result<Vec<(Regex, SchemaNode)>, ValidationError<'a>> { |
| 298 | let Some(Value::Object(patterns)) = parent.get("patternProperties") else { |
| 299 | return Ok(Vec::new()); |
| 300 | }; |
| 301 | |
| 302 | let pat_ctx = ctx.new_at_location("patternProperties"); |
| 303 | let mut result = Vec::with_capacity(patterns.len()); |
| 304 | |
| 305 | for (pattern, schema) in patterns { |
| 306 | let schema_ctx = pat_ctx.new_at_location(pattern.as_str()); |
| 307 | let Ok(regex) = ecma::to_rust_regex(pattern).and_then(|p| Regex::new(&p).map_err(|_| ())) |
| 308 | else { |
| 309 | return Err(ValidationError::format( |
| 310 | Location::new(), |
| 311 | ctx.location().clone(), |
| 312 | schema, |
| 313 | "regex", |
| 314 | )); |
| 315 | }; |
| 316 | let node = compiler::compile(&schema_ctx, schema_ctx.as_resource_ref(schema)) |
| 317 | .map_err(ValidationError::to_owned)?; |
| 318 | result.push((regex, node)); |
| 319 | } |
| 320 | |
| 321 | Ok(result) |
| 322 | } |
| 323 | |
| 324 | fn compile_unevaluated<'a>( |
| 325 | ctx: &compiler::Context<'_>, |
| 326 | parent: &'a Map<String, Value>, |
| 327 | ) -> Result<Option<SchemaNode>, ValidationError<'a>> { |
| 328 | let Some(subschema) = parent.get("unevaluatedProperties") else { |
| 329 | return Ok(None); |
| 330 | }; |
| 331 | |
| 332 | let unevaluated_ctx = ctx.new_at_location("unevaluatedProperties"); |
| 333 | let node = compiler::compile(&unevaluated_ctx, unevaluated_ctx.as_resource_ref(subschema)) |
| 334 | .map_err(ValidationError::to_owned)?; |
| 335 | Ok(Some(node)) |
| 336 | } |
| 337 | |
| 338 | fn compile_all_of<'a>( |
| 339 | ctx: &compiler::Context<'_>, |
| 340 | parent: &'a Map<String, Value>, |
| 341 | ) -> Result<Vec<(SchemaNode, PropertyValidators)>, ValidationError<'a>> { |
| 342 | let Some(Some(subschemas)) = parent.get("allOf").map(Value::as_array) else { |
| 343 | return Ok(Vec::new()); |
| 344 | }; |
| 345 | |
| 346 | let all_of_ctx = ctx.new_at_location("allOf"); |
| 347 | let mut result = Vec::with_capacity(subschemas.len()); |
| 348 | |
| 349 | for (idx, subschema) in subschemas.iter().enumerate() { |
| 350 | let subschema_ctx = all_of_ctx.new_at_location(idx); |
| 351 | let node = compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema)) |
| 352 | .map_err(ValidationError::to_owned)?; |
| 353 | |
| 354 | if let Value::Object(obj) = subschema { |
| 355 | let validators = compile_property_validators(&subschema_ctx, obj)?; |
| 356 | result.push((node, validators)); |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | Ok(result) |
| 361 | } |
| 362 | |
| 363 | fn compile_any_of<'a>( |
| 364 | ctx: &compiler::Context<'_>, |
| 365 | parent: &'a Map<String, Value>, |
| 366 | ) -> Result<Vec<(SchemaNode, PropertyValidators)>, ValidationError<'a>> { |
| 367 | let Some(Some(subschemas)) = parent.get("anyOf").map(Value::as_array) else { |
| 368 | return Ok(Vec::new()); |
| 369 | }; |
| 370 | |
| 371 | let any_of_ctx = ctx.new_at_location("anyOf"); |
| 372 | let mut result = Vec::with_capacity(subschemas.len()); |
| 373 | |
| 374 | for (idx, subschema) in subschemas.iter().enumerate() { |
| 375 | let subschema_ctx = any_of_ctx.new_at_location(idx); |
| 376 | let node = compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema)) |
| 377 | .map_err(ValidationError::to_owned)?; |
| 378 | |
| 379 | if let Value::Object(obj) = subschema { |
| 380 | let validators = compile_property_validators(&subschema_ctx, obj)?; |
| 381 | result.push((node, validators)); |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | Ok(result) |
| 386 | } |
| 387 | |
| 388 | fn compile_one_of<'a>( |
| 389 | ctx: &compiler::Context<'_>, |
| 390 | parent: &'a Map<String, Value>, |
| 391 | ) -> Result<Vec<(SchemaNode, PropertyValidators)>, ValidationError<'a>> { |
| 392 | let Some(Some(subschemas)) = parent.get("oneOf").map(Value::as_array) else { |
| 393 | return Ok(Vec::new()); |
| 394 | }; |
| 395 | |
| 396 | let one_of_ctx = ctx.new_at_location("oneOf"); |
| 397 | let mut result = Vec::with_capacity(subschemas.len()); |
| 398 | |
| 399 | for (idx, subschema) in subschemas.iter().enumerate() { |
| 400 | let subschema_ctx = one_of_ctx.new_at_location(idx); |
| 401 | let node = compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema)) |
| 402 | .map_err(ValidationError::to_owned)?; |
| 403 | |
| 404 | if let Value::Object(obj) = subschema { |
| 405 | let validators = compile_property_validators(&subschema_ctx, obj)?; |
| 406 | result.push((node, validators)); |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | Ok(result) |
| 411 | } |
| 412 | |
| 413 | fn compile_conditional<'a>( |
| 414 | ctx: &compiler::Context<'_>, |
| 415 | parent: &'a Map<String, Value>, |
| 416 | ) -> Result<Option<Box<ConditionalValidators>>, ValidationError<'a>> { |
| 417 | let Some(Value::Object(if_schema)) = parent.get("if") else { |
| 418 | return Ok(None); |
| 419 | }; |
| 420 | |
| 421 | let if_ctx = ctx.new_at_location("if"); |
| 422 | let condition = compiler::compile( |
| 423 | &if_ctx, |
| 424 | if_ctx.as_resource_ref(&Value::Object(if_schema.clone())), |
| 425 | ) |
| 426 | .map_err(ValidationError::to_owned)?; |
| 427 | let if_ = compile_property_validators(&if_ctx, if_schema)?; |
| 428 | |
| 429 | let then_ = if let Some(Value::Object(then_schema)) = parent.get("then") { |
| 430 | let then_ctx = ctx.new_at_location("then"); |
| 431 | Some(compile_property_validators(&then_ctx, then_schema)?) |
| 432 | } else { |
| 433 | None |
| 434 | }; |
| 435 | |
| 436 | let else_ = if let Some(Value::Object(else_schema)) = parent.get("else") { |
| 437 | let else_ctx = ctx.new_at_location("else"); |
| 438 | Some(compile_property_validators(&else_ctx, else_schema)?) |
| 439 | } else { |
| 440 | None |
| 441 | }; |
| 442 | |
| 443 | Ok(Some(Box::new(ConditionalValidators { |
| 444 | condition, |
| 445 | if_, |
| 446 | then_, |
| 447 | else_, |
| 448 | }))) |
| 449 | } |
| 450 | |
| 451 | fn compile_ref<'a>( |
| 452 | ctx: &compiler::Context<'_>, |
| 453 | parent: &Map<String, Value>, |
| 454 | ) -> Result<Option<RefValidator>, ValidationError<'a>> { |
| 455 | let Some(Value::String(reference)) = parent.get("$ref") else { |
| 456 | return Ok(None); |
| 457 | }; |
| 458 | |
| 459 | let resolved = ctx.lookup(reference).map_err(ValidationError::from)?; |
| 460 | |
| 461 | let (contents, resolver, draft) = resolved.into_inner(); |
| 462 | if let Value::Object(subschema) = &contents { |
| 463 | let vocabularies = ctx.registry.find_vocabularies(draft, contents); |
| 464 | let ref_ctx = |
| 465 | ctx.with_resolver_and_draft(resolver, draft, vocabularies, ctx.location().clone()); |
| 466 | let validators = |
| 467 | compile_property_validators(&ref_ctx, subschema).map_err(ValidationError::to_owned)?; |
| 468 | Ok(Some(RefValidator(Box::new(validators)))) |
| 469 | } else { |
| 470 | Ok(None) |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | fn compile_dynamic_ref<'a>( |
| 475 | ctx: &compiler::Context<'_>, |
| 476 | parent: &Map<String, Value>, |
| 477 | ) -> Result<Option<Box<PropertyValidators>>, ValidationError<'a>> { |
| 478 | let Some(Value::String(reference)) = parent.get("$dynamicRef") else { |
| 479 | return Ok(None); |
| 480 | }; |
| 481 | |
| 482 | let resolved = ctx.lookup(reference).map_err(ValidationError::from)?; |
| 483 | |
| 484 | let (contents, resolver, draft) = resolved.into_inner(); |
| 485 | if let Value::Object(subschema) = &contents { |
| 486 | let vocabularies = ctx.registry.find_vocabularies(draft, contents); |
| 487 | let ref_ctx = |
| 488 | ctx.with_resolver_and_draft(resolver, draft, vocabularies, ctx.location().clone()); |
| 489 | let validators = |
| 490 | compile_property_validators(&ref_ctx, subschema).map_err(ValidationError::to_owned)?; |
| 491 | Ok(Some(Box::new(validators))) |
| 492 | } else { |
| 493 | Ok(None) |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | fn compile_recursive_ref<'a>( |
| 498 | ctx: &compiler::Context<'_>, |
| 499 | parent: &Map<String, Value>, |
| 500 | ) -> Result<Option<PendingPropertyValidators>, ValidationError<'a>> { |
| 501 | if !parent.contains_key("$recursiveRef") { |
| 502 | return Ok(None); |
| 503 | } |
| 504 | |
| 505 | // For $recursiveRef, we need to resolve the reference and check if it's already being compiled |
| 506 | let resolved = ctx |
| 507 | .lookup_recursive_reference() |
| 508 | .map_err(ValidationError::from)?; |
| 509 | |
| 510 | // Create context for the resolved reference and check its cache key |
| 511 | let (contents, resolver, draft) = resolved.into_inner(); |
| 512 | if let Value::Object(subschema) = &contents { |
| 513 | let vocabularies = ctx.registry.find_vocabularies(draft, contents); |
| 514 | let ref_ctx = |
| 515 | ctx.with_resolver_and_draft(resolver, draft, vocabularies, ctx.location().clone()); |
| 516 | |
| 517 | // Check if we're already compiling this schema (circular reference) |
| 518 | if let Some(pending) = ref_ctx.get_pending_property_validators_for_schema(subschema) { |
| 519 | return Ok(Some(pending)); |
| 520 | } |
| 521 | |
| 522 | let cache_key = ref_ctx.location_cache_key(); |
| 523 | if let Some(pending) = ref_ctx.get_pending_property_validators(&cache_key) { |
| 524 | // Circular reference detected - return the pending node |
| 525 | return Ok(Some(pending)); |
| 526 | } |
| 527 | |
| 528 | // Not circular, compile normally |
| 529 | let validators = |
| 530 | compile_property_validators(&ref_ctx, subschema).map_err(ValidationError::to_owned)?; |
| 531 | let pending = Shared::new(OnceLock::new()); |
| 532 | let _ = pending.set(validators); |
| 533 | Ok(Some(pending)) |
| 534 | } else { |
| 535 | Ok(None) |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | fn compile_dependent<'a>( |
| 540 | ctx: &compiler::Context<'_>, |
| 541 | parent: &'a Map<String, Value>, |
| 542 | ) -> Result<Vec<(String, PropertyValidators)>, ValidationError<'a>> { |
| 543 | let Some(Value::Object(map)) = parent.get("dependentSchemas") else { |
| 544 | return Ok(Vec::new()); |
| 545 | }; |
| 546 | |
| 547 | let dependent_ctx = ctx.new_at_location("dependentSchemas"); |
| 548 | let mut result = Vec::with_capacity(map.len()); |
| 549 | |
| 550 | for (property, subschema) in map { |
| 551 | if let Value::Object(obj) = subschema { |
| 552 | let property_ctx = dependent_ctx.new_at_location(property.as_str()); |
| 553 | let validators = compile_property_validators(&property_ctx, obj)?; |
| 554 | result.push((property.clone(), validators)); |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | Ok(result) |
| 559 | } |
| 560 | |
| 561 | /// Validator for the `unevaluatedProperties` keyword. |
| 562 | pub(crate) struct UnevaluatedPropertiesValidator { |
| 563 | location: Location, |
| 564 | validators: PropertyValidators, |
| 565 | } |
| 566 | |
| 567 | impl UnevaluatedPropertiesValidator { |
| 568 | pub(crate) fn compile<'a>( |
| 569 | ctx: &'a compiler::Context, |
| 570 | parent: &'a Map<String, Value>, |
| 571 | ) -> CompilationResult<'a> { |
| 572 | let validators = |
| 573 | compile_property_validators(ctx, parent).map_err(ValidationError::to_owned)?; |
| 574 | |
| 575 | Ok(Box::new(UnevaluatedPropertiesValidator { |
| 576 | location: ctx.location().join("unevaluatedProperties"), |
| 577 | validators, |
| 578 | })) |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | impl Validate for UnevaluatedPropertiesValidator { |
| 583 | fn validate<'i>( |
| 584 | &self, |
| 585 | instance: &'i Value, |
| 586 | location: &LazyLocation, |
| 587 | ctx: &mut ValidationContext, |
| 588 | ) -> Result<(), ValidationError<'i>> { |
| 589 | if let Value::Object(properties) = instance { |
| 590 | let mut evaluated = AHashSet::with_capacity(properties.len()); |
| 591 | |
| 592 | // Mark all evaluated properties |
| 593 | self.validators |
| 594 | .mark_evaluated_properties(instance, &mut evaluated, ctx); |
| 595 | |
| 596 | // Early return if all properties are evaluated |
| 597 | if evaluated.len() == properties.len() { |
| 598 | return Ok(()); |
| 599 | } |
| 600 | |
| 601 | // Check for unevaluated properties |
| 602 | let mut unevaluated = Vec::new(); |
| 603 | for (property, value) in properties { |
| 604 | if evaluated.contains(property) { |
| 605 | continue; |
| 606 | } |
| 607 | // Check against unevaluatedProperties schema |
| 608 | if let Some(unevaluated_schema) = &self.validators.unevaluated { |
| 609 | if !unevaluated_schema.is_valid(value, ctx) { |
| 610 | unevaluated.push(property.clone()); |
| 611 | } |
| 612 | } else { |
| 613 | // No unevaluatedProperties schema means false (reject all) |
| 614 | unevaluated.push(property.clone()); |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | if !unevaluated.is_empty() { |
| 619 | return Err(ValidationError::unevaluated_properties( |
| 620 | self.location.clone(), |
| 621 | location.into(), |
| 622 | instance, |
| 623 | unevaluated, |
| 624 | )); |
| 625 | } |
| 626 | } |
| 627 | Ok(()) |
| 628 | } |
| 629 | |
| 630 | fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool { |
| 631 | if let Value::Object(properties) = instance { |
| 632 | let mut evaluated = AHashSet::with_capacity(properties.len()); |
| 633 | self.validators |
| 634 | .mark_evaluated_properties(instance, &mut evaluated, ctx); |
| 635 | |
| 636 | // Early return if all properties are evaluated |
| 637 | if evaluated.len() == properties.len() { |
| 638 | return true; |
| 639 | } |
| 640 | |
| 641 | for (property, value) in properties { |
| 642 | if evaluated.contains(property) { |
| 643 | continue; |
| 644 | } |
| 645 | if let Some(unevaluated_schema) = &self.validators.unevaluated { |
| 646 | if !unevaluated_schema.is_valid(value, ctx) { |
| 647 | return false; |
| 648 | } |
| 649 | } else { |
| 650 | return false; |
| 651 | } |
| 652 | } |
| 653 | } |
| 654 | true |
| 655 | } |
| 656 | |
| 657 | fn evaluate( |
| 658 | &self, |
| 659 | instance: &Value, |
| 660 | location: &LazyLocation, |
| 661 | ctx: &mut ValidationContext, |
| 662 | ) -> EvaluationResult { |
| 663 | if let Value::Object(properties) = instance { |
| 664 | let mut evaluated = AHashSet::with_capacity(properties.len()); |
| 665 | self.validators |
| 666 | .mark_evaluated_properties(instance, &mut evaluated, ctx); |
| 667 | let mut children = Vec::new(); |
| 668 | let mut unevaluated = Vec::new(); |
| 669 | let mut invalid = false; |
| 670 | |
| 671 | for (property, value) in properties { |
| 672 | if evaluated.contains(property) { |
| 673 | continue; |
| 674 | } |
| 675 | if let Some(validator) = &self.validators.unevaluated { |
| 676 | let child = validator.evaluate_instance(value, &location.push(property), ctx); |
| 677 | if !child.valid { |
| 678 | invalid = true; |
| 679 | unevaluated.push(property.clone()); |
| 680 | } |
| 681 | children.push(child); |
| 682 | } else { |
| 683 | invalid = true; |
| 684 | unevaluated.push(property.clone()); |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | let mut errors = Vec::new(); |
| 689 | if !unevaluated.is_empty() { |
| 690 | errors.push(ErrorDescription::from_validation_error( |
| 691 | &ValidationError::unevaluated_properties( |
| 692 | self.location.clone(), |
| 693 | location.into(), |
| 694 | instance, |
| 695 | unevaluated, |
| 696 | ), |
| 697 | )); |
| 698 | } |
| 699 | |
| 700 | if invalid { |
| 701 | EvaluationResult::Invalid { |
| 702 | errors, |
| 703 | children, |
| 704 | annotations: None, |
| 705 | } |
| 706 | } else { |
| 707 | EvaluationResult::Valid { |
| 708 | annotations: None, |
| 709 | children, |
| 710 | } |
| 711 | } |
| 712 | } else { |
| 713 | EvaluationResult::valid_empty() |
| 714 | } |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | pub(crate) fn compile<'a>( |
| 719 | ctx: &'a compiler::Context, |
| 720 | parent: &'a Map<String, Value>, |
| 721 | schema: &'a Value, |
| 722 | ) -> Option<CompilationResult<'a>> { |
| 723 | match schema.as_bool() { |
| 724 | Some(true) => None, // unevaluatedProperties: true is a no-op |
| 725 | _ => Some(UnevaluatedPropertiesValidator::compile(ctx, parent)), |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | #[cfg(test)] |
| 730 | mod tests { |
| 731 | use crate::error::ValidationErrorKind; |
| 732 | use serde_json::json; |
| 733 | |
| 734 | #[test] |
| 735 | fn recursive_ref_preserves_unevaluated_properties() { |
| 736 | let schema = json!({ |
| 737 | "$schema": "https://json-schema.org/draft/2019-09/schema", |
| 738 | "$id": "https://example.com/root", |
| 739 | "$recursiveAnchor": true, |
| 740 | "type": "object", |
| 741 | "properties": { |
| 742 | "child": { |
| 743 | "type": "object", |
| 744 | "properties": { |
| 745 | "child": { "$recursiveRef": "#" } |
| 746 | }, |
| 747 | "unevaluatedProperties": false |
| 748 | } |
| 749 | }, |
| 750 | "unevaluatedProperties": false |
| 751 | }); |
| 752 | |
| 753 | let validator = crate::options().build(&schema).expect("schema compiles"); |
| 754 | |
| 755 | let valid = json!({"child": {"child": {}}}); |
| 756 | assert!( |
| 757 | validator.is_valid(&valid), |
| 758 | "expected recursive schema without extras to be valid" |
| 759 | ); |
| 760 | |
| 761 | let invalid = json!({"child": {"child": {"unexpected": 1}}}); |
| 762 | assert!( |
| 763 | !validator.is_valid(&invalid), |
| 764 | "unexpected properties should be rejected" |
| 765 | ); |
| 766 | |
| 767 | let errors: Vec<_> = validator.iter_errors(&invalid).collect(); |
| 768 | assert!( |
| 769 | errors.iter().any(|err| matches!( |
| 770 | err.kind(), |
| 771 | ValidationErrorKind::UnevaluatedProperties { .. } |
| 772 | )), |
| 773 | "expected unevaluatedProperties error, got {errors:?}" |
| 774 | ); |
| 775 | } |
| 776 | } |