| 1 | use crate::{ |
| 2 | compiler, keywords::CompilationResult, paths::Location, types::JsonType, validator::Validate, |
| 3 | ValidationError, |
| 4 | }; |
| 5 | use serde_json::{Map, Value}; |
| 6 | |
| 7 | fn compile_reference_validator<'a>( |
| 8 | ctx: &compiler::Context, |
| 9 | reference: &str, |
| 10 | keyword: &str, |
| 11 | ) -> Option<CompilationResult<'a>> { |
| 12 | let current_location = match ctx.absolute_location_uri().map_err(ValidationError::from) { |
| 13 | Ok(uri) => uri, |
| 14 | Err(error) => return Some(Err(error)), |
| 15 | }; |
| 16 | let alias = match ctx |
| 17 | .resolve_reference_uri(reference) |
| 18 | .map_err(ValidationError::from) |
| 19 | { |
| 20 | Ok(uri) => uri, |
| 21 | Err(error) => return Some(Err(error)), |
| 22 | }; |
| 23 | |
| 24 | if alias == current_location |
| 25 | || (reference.is_empty() && alias.strip_fragment() == current_location.strip_fragment()) |
| 26 | { |
| 27 | // Direct self-reference would recurse indefinitely, treat it as an annotation-only schema. |
| 28 | // Empty string $ref ("") is a same-document reference per RFC 3986, equivalent to "#" |
| 29 | return None; |
| 30 | } |
| 31 | |
| 32 | match ctx.lookup_maybe_recursive(reference) { |
| 33 | Ok(Some(validator)) => return Some(Ok(validator)), |
| 34 | Ok(None) => {} |
| 35 | Err(error) => return Some(Err(error)), |
| 36 | } |
| 37 | |
| 38 | if let Err(error) = ctx.mark_seen(reference) { |
| 39 | return Some(Err(ValidationError::from(error))); |
| 40 | } |
| 41 | |
| 42 | let (contents, resolver, draft) = match ctx.lookup(reference) { |
| 43 | Ok(resolved) => resolved.into_inner(), |
| 44 | Err(error) => return Some(Err(ValidationError::from(error))), |
| 45 | }; |
| 46 | let vocabularies = ctx.registry.find_vocabularies(draft, contents); |
| 47 | let resource_ref = draft.create_resource_ref(contents); |
| 48 | let ctx = ctx.with_resolver_and_draft( |
| 49 | resolver, |
| 50 | resource_ref.draft(), |
| 51 | vocabularies, |
| 52 | ctx.location().join(keyword), |
| 53 | ); |
| 54 | Some( |
| 55 | compiler::compile_with_alias(&ctx, resource_ref, alias) |
| 56 | .map(|node| { |
| 57 | Box::new(node.clone_with_location(ctx.location().clone(), ctx.base_uri())) |
| 58 | as Box<dyn Validate> |
| 59 | }) |
| 60 | .map_err(ValidationError::to_owned), |
| 61 | ) |
| 62 | } |
| 63 | |
| 64 | fn compile_recursive_validator<'a>( |
| 65 | ctx: &compiler::Context, |
| 66 | reference: &str, |
| 67 | ) -> CompilationResult<'a> { |
| 68 | // Check if this is a circular reference first |
| 69 | match ctx.lookup_maybe_recursive(reference) { |
| 70 | Ok(Some(validator)) => return Ok(validator), |
| 71 | Ok(None) => {} |
| 72 | Err(error) => return Err(error), |
| 73 | } |
| 74 | |
| 75 | if let Err(error) = ctx.mark_seen(reference) { |
| 76 | return Err(ValidationError::from(error)); |
| 77 | } |
| 78 | |
| 79 | let alias = ctx |
| 80 | .resolve_reference_uri(reference) |
| 81 | .map_err(ValidationError::from)?; |
| 82 | let resolved = ctx |
| 83 | .lookup_recursive_reference() |
| 84 | .map_err(ValidationError::from)?; |
| 85 | let (contents, resolver, draft) = resolved.into_inner(); |
| 86 | let vocabularies = ctx.registry.find_vocabularies(draft, contents); |
| 87 | let resource_ref = draft.create_resource_ref(contents); |
| 88 | let ctx = ctx.with_resolver_and_draft( |
| 89 | resolver, |
| 90 | resource_ref.draft(), |
| 91 | vocabularies, |
| 92 | ctx.location().join("$recursiveRef"), |
| 93 | ); |
| 94 | compiler::compile_with_alias(&ctx, resource_ref, alias) |
| 95 | .map(|node| { |
| 96 | Box::new(node.clone_with_location(ctx.location().clone(), ctx.base_uri())) |
| 97 | as Box<dyn Validate> |
| 98 | }) |
| 99 | .map_err(ValidationError::to_owned) |
| 100 | } |
| 101 | |
| 102 | fn invalid_reference<'a>(ctx: &compiler::Context, schema: &'a Value) -> ValidationError<'a> { |
| 103 | ValidationError::single_type_error( |
| 104 | Location::new(), |
| 105 | ctx.location().clone(), |
| 106 | schema, |
| 107 | JsonType::String, |
| 108 | ) |
| 109 | } |
| 110 | |
| 111 | #[inline] |
| 112 | pub(crate) fn compile_impl<'a>( |
| 113 | ctx: &compiler::Context, |
| 114 | _parent: &'a Map<String, Value>, |
| 115 | schema: &'a Value, |
| 116 | keyword: &str, |
| 117 | ) -> Option<CompilationResult<'a>> { |
| 118 | if let Some(reference) = schema.as_str() { |
| 119 | compile_reference_validator(ctx, reference, keyword) |
| 120 | } else { |
| 121 | Some(Err(invalid_reference(ctx, schema))) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | #[inline] |
| 126 | pub(crate) fn compile_dynamic_ref<'a>( |
| 127 | ctx: &compiler::Context, |
| 128 | parent: &'a Map<String, Value>, |
| 129 | schema: &'a Value, |
| 130 | ) -> Option<CompilationResult<'a>> { |
| 131 | compile_impl(ctx, parent, schema, "$dynamicRef") |
| 132 | } |
| 133 | |
| 134 | #[inline] |
| 135 | pub(crate) fn compile_ref<'a>( |
| 136 | ctx: &compiler::Context, |
| 137 | parent: &'a Map<String, Value>, |
| 138 | schema: &'a Value, |
| 139 | ) -> Option<CompilationResult<'a>> { |
| 140 | compile_impl(ctx, parent, schema, "$ref") |
| 141 | } |
| 142 | |
| 143 | #[inline] |
| 144 | pub(crate) fn compile_recursive_ref<'a>( |
| 145 | ctx: &compiler::Context, |
| 146 | _: &'a Map<String, Value>, |
| 147 | schema: &'a Value, |
| 148 | ) -> Option<CompilationResult<'a>> { |
| 149 | Some( |
| 150 | schema |
| 151 | .as_str() |
| 152 | .ok_or_else(|| invalid_reference(ctx, schema)) |
| 153 | .and_then(|reference| compile_recursive_validator(ctx, reference)), |
| 154 | ) |
| 155 | } |
| 156 | |
| 157 | #[cfg(test)] |
| 158 | mod tests { |
| 159 | use crate::tests_util; |
| 160 | use ahash::HashMap; |
| 161 | use referencing::{Retrieve, Uri}; |
| 162 | use serde_json::{json, Value}; |
| 163 | use test_case::test_case; |
| 164 | |
| 165 | struct MyRetrieve; |
| 166 | |
| 167 | impl Retrieve for MyRetrieve { |
| 168 | fn retrieve( |
| 169 | &self, |
| 170 | uri: &Uri<String>, |
| 171 | ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> { |
| 172 | match uri.path().as_str() { |
| 173 | "/indirection" => Ok(json!({ |
| 174 | "$id": "/indirection", |
| 175 | "baz": { |
| 176 | "$ref": "/types#/foo" |
| 177 | } |
| 178 | })), |
| 179 | "/types" => Ok(json!({ |
| 180 | "$id": "/types", |
| 181 | "foo": { |
| 182 | "$id": "#/foo", |
| 183 | "$ref": "#/bar" |
| 184 | }, |
| 185 | "bar": { |
| 186 | "type": "integer" |
| 187 | } |
| 188 | })), |
| 189 | _ => panic!("Not found"), |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | #[test] |
| 195 | fn custom_retrieve_can_load_remote() { |
| 196 | let retriever = MyRetrieve; |
| 197 | let uri = Uri::try_from("https://example.com/types".to_string()).expect("valid uri"); |
| 198 | let value: Value = retriever |
| 199 | .retrieve(&uri) |
| 200 | .expect("should load the remote document"); |
| 201 | let bar = value |
| 202 | .get("bar") |
| 203 | .and_then(|schema| schema.get("type")) |
| 204 | .cloned(); |
| 205 | assert_eq!(bar, Some(json!("integer"))); |
| 206 | } |
| 207 | |
| 208 | struct TestRetrieve { |
| 209 | storage: HashMap<String, Value>, |
| 210 | } |
| 211 | |
| 212 | impl Retrieve for TestRetrieve { |
| 213 | fn retrieve( |
| 214 | &self, |
| 215 | uri: &Uri<String>, |
| 216 | ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> { |
| 217 | self.storage |
| 218 | .get(uri.path().as_str()) |
| 219 | .cloned() |
| 220 | .ok_or_else(|| "Document not found".into()) |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | struct NestedRetrieve; |
| 225 | |
| 226 | impl Retrieve for NestedRetrieve { |
| 227 | fn retrieve( |
| 228 | &self, |
| 229 | uri: &Uri<String>, |
| 230 | ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> { |
| 231 | match uri.as_str() { |
| 232 | "foo://schema_2.json" => Ok(json!({ |
| 233 | "$id": "foo://schema_2.json", |
| 234 | "type": "string" |
| 235 | })), |
| 236 | _ => panic!("Unexpected URI: {}", uri.path()), |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | struct FragmentRetrieve; |
| 242 | |
| 243 | impl Retrieve for FragmentRetrieve { |
| 244 | fn retrieve( |
| 245 | &self, |
| 246 | uri: &Uri<String>, |
| 247 | ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> { |
| 248 | match uri.path().as_str() { |
| 249 | "/tmp/schemas/one.json" => Ok(json!({ |
| 250 | "$defs": { |
| 251 | "obj": { |
| 252 | "$ref": "other.json#/$defs/obj" |
| 253 | } |
| 254 | } |
| 255 | })), |
| 256 | "/tmp/schemas/other.json" => Ok(json!({ |
| 257 | "$defs": { |
| 258 | "obj": { |
| 259 | "type": "number" |
| 260 | } |
| 261 | } |
| 262 | })), |
| 263 | _ => panic!("Unexpected URI: {}", uri.path()), |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | #[test_case( |
| 269 | &json!({ |
| 270 | "properties": { |
| 271 | "foo": {"$ref": "#/definitions/foo"} |
| 272 | }, |
| 273 | "definitions": { |
| 274 | "foo": {"type": "string"} |
| 275 | } |
| 276 | }), |
| 277 | &json!({"foo": 42}), |
| 278 | "/properties/foo/$ref/type" |
| 279 | )] |
| 280 | fn location(schema: &Value, instance: &Value, expected: &str) { |
| 281 | tests_util::assert_schema_location(schema, instance, expected); |
| 282 | } |
| 283 | |
| 284 | #[test] |
| 285 | fn multiple_errors_locations() { |
| 286 | let instance = json!({ |
| 287 | "things": [ |
| 288 | { "code": "CC" }, |
| 289 | { "code": "CC" }, |
| 290 | ] |
| 291 | }); |
| 292 | let schema = json!({ |
| 293 | "type": "object", |
| 294 | "properties": { |
| 295 | "things": { |
| 296 | "type": "array", |
| 297 | "items": { |
| 298 | "type": "object", |
| 299 | "properties": { |
| 300 | "code": { |
| 301 | "type": "string", |
| 302 | "$ref": "#/$defs/codes" |
| 303 | } |
| 304 | }, |
| 305 | "required": ["code"] |
| 306 | } |
| 307 | } |
| 308 | }, |
| 309 | "required": ["things"], |
| 310 | "$defs": { "codes": { "enum": ["AA", "BB"] } } |
| 311 | }); |
| 312 | let validator = crate::validator_for(&schema).expect("Invalid schema"); |
| 313 | let mut iter = validator.iter_errors(&instance); |
| 314 | let expected = "/properties/things/items/properties/code/$ref/enum"; |
| 315 | assert_eq!( |
| 316 | iter.next() |
| 317 | .expect("Should be present") |
| 318 | .schema_path() |
| 319 | .to_string(), |
| 320 | expected |
| 321 | ); |
| 322 | assert_eq!( |
| 323 | iter.next() |
| 324 | .expect("Should be present") |
| 325 | .schema_path() |
| 326 | .to_string(), |
| 327 | expected |
| 328 | ); |
| 329 | } |
| 330 | |
| 331 | #[test] |
| 332 | fn test_relative_base_uri() { |
| 333 | let schema = json!({ |
| 334 | "$id": "/root", |
| 335 | "$ref": "#/foo", |
| 336 | "foo": { |
| 337 | "$id": "#/foo", |
| 338 | "$ref": "#/bar" |
| 339 | }, |
| 340 | "bar": { |
| 341 | "$id": "#/bar", |
| 342 | "type": "integer" |
| 343 | }, |
| 344 | }); |
| 345 | let validator = crate::validator_for(&schema).expect("Invalid schema"); |
| 346 | assert!(validator.is_valid(&json!(2))); |
| 347 | assert!(!validator.is_valid(&json!("a"))); |
| 348 | } |
| 349 | |
| 350 | #[test_case( |
| 351 | &json!({ |
| 352 | "$id": "https://example.com/schema.json", |
| 353 | "$schema": "https://json-schema.org/draft/2020-12/schema", |
| 354 | "type": "object", |
| 355 | "properties": { |
| 356 | "foo": { |
| 357 | "type": "array", |
| 358 | "items": { "$ref": "#/$defs/item" } |
| 359 | } |
| 360 | }, |
| 361 | "$defs": { |
| 362 | "item": { |
| 363 | "type": "object", |
| 364 | "required": ["name", "value"], |
| 365 | "properties": { |
| 366 | "name": { "type": "string" }, |
| 367 | "value": { "type": "boolean" } |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | }), |
| 372 | &json!({ |
| 373 | "foo": [{"name": "item1", "value": true}] |
| 374 | }), |
| 375 | vec![ |
| 376 | ("", "/properties"), |
| 377 | ("/foo", "/properties/foo/items"), |
| 378 | ("/foo/0", "/properties/foo/items/$ref/properties"), |
| 379 | ] |
| 380 | ; "standard $ref")] |
| 381 | #[test_case( |
| 382 | &json!({ |
| 383 | "$id": "https://example.com/schema.json", |
| 384 | "$schema": "https://json-schema.org/draft/2019-09/schema", |
| 385 | "$recursiveAnchor": true, |
| 386 | "type": "object", |
| 387 | "properties": { |
| 388 | "name": { "type": "string" }, |
| 389 | "child": { "$recursiveRef": "#" } |
| 390 | } |
| 391 | }), |
| 392 | &json!({ |
| 393 | "name": "parent", |
| 394 | "child": { |
| 395 | "name": "child", |
| 396 | "child": { "name": "grandchild" } |
| 397 | } |
| 398 | }), |
| 399 | vec![ |
| 400 | ("", "/properties"), |
| 401 | ("/child", "/properties/child/$recursiveRef/properties"), |
| 402 | ("/child/child", "/properties/child/$recursiveRef/properties"), |
| 403 | ] |
| 404 | ; "$recursiveRef")] |
| 405 | fn keyword_locations(schema: &Value, instance: &Value, expected: Vec<(&str, &str)>) { |
| 406 | let validator = crate::validator_for(schema).expect("Invalid schema"); |
| 407 | for (pointer, keyword_location) in expected { |
| 408 | tests_util::assert_keyword_location(&validator, instance, pointer, keyword_location); |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | #[test] |
| 413 | fn test_resolving_finds_references_in_referenced_resources() { |
| 414 | let schema = json!({"$ref": "/indirection#/baz"}); |
| 415 | |
| 416 | let validator = crate::options() |
| 417 | .with_retriever(MyRetrieve) |
| 418 | .build(&schema) |
| 419 | .expect("Failed to build validator"); |
| 420 | |
| 421 | assert!(validator.is_valid(&json!(2))); |
| 422 | assert!(!validator.is_valid(&json!(""))); |
| 423 | } |
| 424 | |
| 425 | #[test_case( |
| 426 | &json!({"$ref": "/doc#/definitions/foo"}), |
| 427 | &json!({ |
| 428 | "$id": "/doc", |
| 429 | "definitions": { |
| 430 | "foo": {"type": "integer"} |
| 431 | } |
| 432 | }), |
| 433 | None |
| 434 | ; "basic_fragment" |
| 435 | )] |
| 436 | #[test_case( |
| 437 | &json!({"$ref": "/doc1#/definitions/foo"}), |
| 438 | &json!({ |
| 439 | "$id": "/doc1", |
| 440 | "definitions": { |
| 441 | "foo": {"$ref": "#/definitions/bar"}, |
| 442 | "bar": {"type": "integer"} |
| 443 | } |
| 444 | }), |
| 445 | None |
| 446 | ; "intermediate_reference" |
| 447 | )] |
| 448 | #[test_case( |
| 449 | &json!({"$ref": "/doc2#/refs/first"}), |
| 450 | &json!({ |
| 451 | "$id": "/doc2", |
| 452 | "refs": { |
| 453 | "first": {"$ref": "/doc3#/refs/second"} |
| 454 | } |
| 455 | }), |
| 456 | Some(&json!({ |
| 457 | "/doc3": { |
| 458 | "$id": "/doc3", |
| 459 | "refs": { |
| 460 | "second": {"type": "integer"} |
| 461 | } |
| 462 | } |
| 463 | })) |
| 464 | ; "multiple_documents" |
| 465 | )] |
| 466 | #[test_case( |
| 467 | &json!({"$ref": "/doc4#/defs/foo"}), |
| 468 | &json!({ |
| 469 | "$id": "/doc4", |
| 470 | "defs": { |
| 471 | "foo": { |
| 472 | "$id": "#/defs/foo", |
| 473 | "$ref": "#/defs/bar" |
| 474 | }, |
| 475 | "bar": {"type": "integer"} |
| 476 | } |
| 477 | }), |
| 478 | None |
| 479 | ; "id_and_fragment" |
| 480 | )] |
| 481 | #[test_case( |
| 482 | &json!({"$ref": "/doc5#/outer"}), |
| 483 | &json!({ |
| 484 | "$id": "/doc5", |
| 485 | "outer": { |
| 486 | "$ref": "#/middle", |
| 487 | }, |
| 488 | "middle": { |
| 489 | "$id": "#/middle", |
| 490 | "$ref": "#/inner" |
| 491 | }, |
| 492 | "inner": {"type": "integer"} |
| 493 | }), |
| 494 | None |
| 495 | ; "nested_references" |
| 496 | )] |
| 497 | fn test_fragment_resolution(schema: &Value, root: &Value, extra: Option<&Value>) { |
| 498 | let mut storage = HashMap::default(); |
| 499 | |
| 500 | let doc_path = schema["$ref"] |
| 501 | .as_str() |
| 502 | .and_then(|r| r.split('#').next()) |
| 503 | .expect("Invalid $ref"); |
| 504 | |
| 505 | storage.insert(doc_path.to_string(), root.clone()); |
| 506 | |
| 507 | if let Some(extra) = extra { |
| 508 | for (path, document) in extra.as_object().unwrap() { |
| 509 | storage.insert(path.clone(), document.clone()); |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | let retriever = TestRetrieve { storage }; |
| 514 | |
| 515 | let validator = crate::options() |
| 516 | .with_retriever(retriever) |
| 517 | .build(schema) |
| 518 | .expect("Invalid schema"); |
| 519 | |
| 520 | assert!(validator.is_valid(&json!(42))); |
| 521 | assert!(!validator.is_valid(&json!("string"))); |
| 522 | } |
| 523 | |
| 524 | #[test] |
| 525 | fn test_infinite_loop() { |
| 526 | let validator = crate::validator_for(&json!({"$ref": "#"})).expect("Invalid schema"); |
| 527 | assert!(validator.is_valid(&json!(42))); |
| 528 | } |
| 529 | |
| 530 | #[test] |
| 531 | fn test_nested_external_reference() { |
| 532 | let schema = json!({ |
| 533 | "$id": "foo://schema_1.json", |
| 534 | "$ref": "#/$defs/a/b", |
| 535 | "$defs": { |
| 536 | "a": { |
| 537 | "b": { |
| 538 | "description": "nested schema with external ref", |
| 539 | "$ref": "foo://schema_2.json" |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | }); |
| 544 | |
| 545 | let validator = crate::options() |
| 546 | .with_retriever(NestedRetrieve) |
| 547 | .build(&schema) |
| 548 | .expect("Failed to build validator"); |
| 549 | |
| 550 | assert!(validator.is_valid(&json!("test"))); |
| 551 | assert!(!validator.is_valid(&json!(42))); |
| 552 | } |
| 553 | |
| 554 | #[test] |
| 555 | fn test_relative_reference_with_fragment() { |
| 556 | let schema = json!({ |
| 557 | "$id": "file:///tmp/schemas/root.json", |
| 558 | "$ref": "one.json#/$defs/obj" |
| 559 | }); |
| 560 | |
| 561 | let validator = crate::options() |
| 562 | .with_retriever(FragmentRetrieve) |
| 563 | .build(&schema) |
| 564 | .expect("Failed to build validator"); |
| 565 | |
| 566 | assert!(validator.is_valid(&json!(42))); |
| 567 | assert!(!validator.is_valid(&json!("string"))); |
| 568 | } |
| 569 | |
| 570 | #[test] |
| 571 | fn test_missing_file() { |
| 572 | let schema = json!({"$ref": "./virtualNetwork.json"}); |
| 573 | let error = crate::validator_for(&schema).expect_err("Should fail"); |
| 574 | assert_eq!( |
| 575 | error.to_string(), |
| 576 | "Resource './virtualNetwork.json' is not present in a registry and retrieving it failed: No base URI is available" |
| 577 | ); |
| 578 | } |
| 579 | |
| 580 | #[test] |
| 581 | fn test_empty_ref_no_stack_overflow() { |
| 582 | // Empty string is a same-document reference per RFC 3986, should behave like $ref: "#" |
| 583 | let schema = json!({"$ref": ""}); |
| 584 | let instance = json!(-1); |
| 585 | |
| 586 | // Should compile without error and validate without stack overflow |
| 587 | let validator = crate::validator_for(&schema).expect("Should compile"); |
| 588 | assert!(validator.is_valid(&instance)); |
| 589 | } |
| 590 | |
| 591 | struct IndirectExternalRetrieve; |
| 592 | |
| 593 | impl Retrieve for IndirectExternalRetrieve { |
| 594 | fn retrieve( |
| 595 | &self, |
| 596 | uri: &Uri<String>, |
| 597 | ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> { |
| 598 | match uri.as_str() { |
| 599 | "file:///ext.yaml" => Ok(json!({ |
| 600 | "components": { |
| 601 | "schemas": { |
| 602 | "c3": { |
| 603 | "type": "integer" |
| 604 | } |
| 605 | } |
| 606 | } |
| 607 | })), |
| 608 | _ => Err(format!("Unexpected URI: {uri}").into()), |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | #[test] |
| 614 | fn test_indirect_local_refs_to_external_resource() { |
| 615 | // GH-892: Chained local $refs where the final ref points to an external resource |
| 616 | // should properly discover and retrieve the external resource. |
| 617 | // |
| 618 | // The chain is: |
| 619 | // root $ref -> #/components/schemas/c1 |
| 620 | // c1 $ref -> #/components/schemas/c2 |
| 621 | // c2 $ref -> ext.yaml#/components/schemas/c3 (EXTERNAL) |
| 622 | let schema = json!({ |
| 623 | "$id": "file:///tmp", |
| 624 | "$ref": "#/components/schemas/c1", |
| 625 | "components": { |
| 626 | "schemas": { |
| 627 | "c1": { |
| 628 | "$ref": "#/components/schemas/c2" |
| 629 | }, |
| 630 | "c2": { |
| 631 | "$ref": "ext.yaml#/components/schemas/c3" |
| 632 | } |
| 633 | } |
| 634 | } |
| 635 | }); |
| 636 | |
| 637 | let validator = crate::options() |
| 638 | .with_retriever(IndirectExternalRetrieve) |
| 639 | .build(&schema) |
| 640 | .expect("Failed to build validator - external resource was not discovered"); |
| 641 | |
| 642 | assert!(validator.is_valid(&json!(42))); |
| 643 | assert!(!validator.is_valid(&json!("string"))); |
| 644 | } |
| 645 | |
| 646 | #[test] |
| 647 | fn test_local_ref_with_nested_external_ref_in_properties() { |
| 648 | // GH-892 follow-up: Local $ref points to a schema that has an external $ref |
| 649 | // nested within properties (not a direct $ref chain). |
| 650 | // |
| 651 | // The structure is: |
| 652 | // root $ref -> #/components/schemas/c1 |
| 653 | // c1 is a full schema with type/properties |
| 654 | // c1.properties.p contains an external $ref |
| 655 | let schema = json!({ |
| 656 | "$id": "file:///tmp", |
| 657 | "$ref": "#/components/schemas/c1", |
| 658 | "components": { |
| 659 | "schemas": { |
| 660 | "c1": { |
| 661 | "type": "object", |
| 662 | "properties": { |
| 663 | "p": { |
| 664 | "$ref": "ext.yaml#/components/schemas/c3" |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | } |
| 669 | } |
| 670 | }); |
| 671 | |
| 672 | let validator = crate::options() |
| 673 | .with_retriever(IndirectExternalRetrieve) |
| 674 | .build(&schema) |
| 675 | .expect("Failed to build validator - external resource was not discovered"); |
| 676 | |
| 677 | assert!(validator.is_valid(&json!({"p": 42}))); |
| 678 | assert!(!validator.is_valid(&json!({"p": "string"}))); |
| 679 | } |
| 680 | |
| 681 | struct CrossFileRetrieve; |
| 682 | |
| 683 | impl Retrieve for CrossFileRetrieve { |
| 684 | fn retrieve( |
| 685 | &self, |
| 686 | uri: &Uri<String>, |
| 687 | ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> { |
| 688 | match uri.as_str() { |
| 689 | "file:///tmp/json" => Ok(json!({ |
| 690 | "components": { |
| 691 | "schemas": { |
| 692 | "c1": { |
| 693 | "type": "array", |
| 694 | "items": { |
| 695 | "$ref": "#/components/schemas/c2" |
| 696 | } |
| 697 | }, |
| 698 | "c2": { |
| 699 | "$ref": "ext.json#/components/schemas/c3" |
| 700 | } |
| 701 | } |
| 702 | } |
| 703 | })), |
| 704 | "file:///tmp/ext.json" => Ok(json!({ |
| 705 | "components": { |
| 706 | "schemas": { |
| 707 | "c3": { |
| 708 | "type": "integer" |
| 709 | } |
| 710 | } |
| 711 | } |
| 712 | })), |
| 713 | _ => Err(format!("Unexpected URI: {uri}").into()), |
| 714 | } |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | #[test] |
| 719 | fn test_cross_file_local_ref_resolution() { |
| 720 | // GH-892: External ref with fragment pointing to a schema that has local refs. |
| 721 | // The local refs within the external file need to resolve against that file's |
| 722 | // document root, not the original schema's root. |
| 723 | // |
| 724 | // Structure: |
| 725 | // root $ref -> file:///tmp/json#/components/schemas/c1 |
| 726 | // /tmp/json has: |
| 727 | // c1.items.$ref -> #/components/schemas/c2 (local ref within /tmp/json) |
| 728 | // c2.$ref -> ext.json#/components/schemas/c3 (external ref) |
| 729 | let schema = json!({ |
| 730 | "$ref": "file:///tmp/json#/components/schemas/c1" |
| 731 | }); |
| 732 | |
| 733 | let validator = crate::options() |
| 734 | .with_retriever(CrossFileRetrieve) |
| 735 | .build(&schema) |
| 736 | .expect("Failed to build validator - external resource was not discovered"); |
| 737 | |
| 738 | assert!(validator.is_valid(&json!([1, 2, 3]))); |
| 739 | assert!(!validator.is_valid(&json!(["a", "b"]))); |
| 740 | } |
| 741 | |
| 742 | #[test] |
| 743 | fn test_circular_local_refs_compile() { |
| 744 | let schema = json!({ |
| 745 | "$defs": { |
| 746 | "a": {"$ref": "#/$defs/b"}, |
| 747 | "b": {"$ref": "#/$defs/a"} |
| 748 | }, |
| 749 | "$ref": "#/$defs/a" |
| 750 | }); |
| 751 | let validator = crate::validator_for(&schema).expect("Should compile"); |
| 752 | |
| 753 | // A pure $ref cycle is equivalent to `true` schema |
| 754 | for instance in [ |
| 755 | json!(42), |
| 756 | json!("string"), |
| 757 | json!(null), |
| 758 | json!({"nested": [1, 2, 3]}), |
| 759 | ] { |
| 760 | assert!(validator.is_valid(&instance)); |
| 761 | assert!(validator.validate(&instance).is_ok()); |
| 762 | assert_eq!(validator.iter_errors(&instance).count(), 0); |
| 763 | assert!(validator.evaluate(&instance).flag().valid); |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | #[test] |
| 768 | fn test_circular_refs_with_constraints() { |
| 769 | let schema = json!({ |
| 770 | "$defs": { |
| 771 | "node": { |
| 772 | "type": "object", |
| 773 | "properties": { |
| 774 | "value": {"type": "integer"}, |
| 775 | "next": {"$ref": "#/$defs/node"} |
| 776 | } |
| 777 | } |
| 778 | }, |
| 779 | "$ref": "#/$defs/node" |
| 780 | }); |
| 781 | let validator = crate::validator_for(&schema).expect("Should compile"); |
| 782 | |
| 783 | let valid = json!({"value": 1, "next": {"value": 2, "next": {"value": 3}}}); |
| 784 | assert!(validator.is_valid(&valid)); |
| 785 | assert!(validator.validate(&valid).is_ok()); |
| 786 | assert_eq!(validator.iter_errors(&valid).count(), 0); |
| 787 | |
| 788 | let invalid = json!({"value": "not an int"}); |
| 789 | assert!(!validator.is_valid(&invalid)); |
| 790 | assert!(validator.validate(&invalid).is_err()); |
| 791 | assert!(validator.iter_errors(&invalid).count() > 0); |
| 792 | |
| 793 | let invalid_nested = json!({"value": 1, "next": {"value": "bad"}}); |
| 794 | assert!(!validator.is_valid(&invalid_nested)); |
| 795 | assert!(validator.validate(&invalid_nested).is_err()); |
| 796 | assert!(validator.iter_errors(&invalid_nested).count() > 0); |
| 797 | } |
| 798 | |
| 799 | #[test] |
| 800 | fn test_longer_circular_chain() { |
| 801 | let schema = json!({ |
| 802 | "$defs": { |
| 803 | "a": {"$ref": "#/$defs/b"}, |
| 804 | "b": {"$ref": "#/$defs/c"}, |
| 805 | "c": {"$ref": "#/$defs/a"} |
| 806 | }, |
| 807 | "$ref": "#/$defs/a" |
| 808 | }); |
| 809 | let validator = crate::validator_for(&schema).expect("Should compile"); |
| 810 | |
| 811 | let instance = json!({"any": "value"}); |
| 812 | assert!(validator.is_valid(&instance)); |
| 813 | assert!(validator.validate(&instance).is_ok()); |
| 814 | assert_eq!(validator.iter_errors(&instance).count(), 0); |
| 815 | assert!(validator.evaluate(&instance).flag().valid); |
| 816 | } |
| 817 | |
| 818 | #[test] |
| 819 | fn test_dependencies_with_array_form() { |
| 820 | // Tests NodeValidators::Array branch via dependencies with array form |
| 821 | let schema = json!({ |
| 822 | "dependencies": { |
| 823 | "foo": ["bar", "baz"] |
| 824 | } |
| 825 | }); |
| 826 | let validator = crate::validator_for(&schema).expect("Should compile"); |
| 827 | |
| 828 | let valid = json!({"foo": 1, "bar": 2, "baz": 3}); |
| 829 | assert!(validator.is_valid(&valid)); |
| 830 | assert!(validator.validate(&valid).is_ok()); |
| 831 | assert_eq!(validator.iter_errors(&valid).count(), 0); |
| 832 | assert!(validator.evaluate(&valid).flag().valid); |
| 833 | |
| 834 | let invalid = json!({"foo": 1}); |
| 835 | assert!(!validator.is_valid(&invalid)); |
| 836 | assert!(validator.validate(&invalid).is_err()); |
| 837 | assert!(validator.iter_errors(&invalid).count() > 0); |
| 838 | assert!(!validator.evaluate(&invalid).flag().valid); |
| 839 | } |
| 840 | |
| 841 | #[test] |
| 842 | fn test_dependent_required_array_form() { |
| 843 | // Tests NodeValidators::Array branch via dependentRequired (Draft 2019-09+) |
| 844 | let schema = json!({ |
| 845 | "$schema": "https://json-schema.org/draft/2019-09/schema", |
| 846 | "dependentRequired": { |
| 847 | "foo": ["bar"] |
| 848 | } |
| 849 | }); |
| 850 | let validator = crate::validator_for(&schema).expect("Should compile"); |
| 851 | |
| 852 | let valid = json!({"foo": 1, "bar": 2}); |
| 853 | assert!(validator.is_valid(&valid)); |
| 854 | assert!(validator.validate(&valid).is_ok()); |
| 855 | assert_eq!(validator.iter_errors(&valid).count(), 0); |
| 856 | assert!(validator.evaluate(&valid).flag().valid); |
| 857 | |
| 858 | let invalid = json!({"foo": 1}); |
| 859 | assert!(!validator.is_valid(&invalid)); |
| 860 | assert!(validator.validate(&invalid).is_err()); |
| 861 | assert!(validator.iter_errors(&invalid).count() > 0); |
| 862 | } |
| 863 | } |