1// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15// author xeipuuv 16// author-github https://github.com/xeipuuv 17// author-mail xeipuuv@gmail.com 18// 19// repository-name gojsonschema 20// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. 21// 22// description Extends Schema and subSchema, implements the validation phase. 23// 24// created 28-02-2013 25 26package gojsonschema 27 28import ( 29 "encoding/json" 30 "reflect" 31 "regexp" 32 "strconv" 33 "strings" 34 "unicode/utf8" 35) 36 37func Validate(ls JSONLoader, ld JSONLoader) (*Result, error) { 38 39 var err error 40 41 // load schema 42 43 schema, err := NewSchema(ls) 44 if err != nil { 45 return nil, err 46 } 47 48 // begine validation 49 50 return schema.Validate(ld) 51 52} 53 54func (v *Schema) Validate(l JSONLoader) (*Result, error) { 55 56 // load document 57 58 root, err := l.LoadJSON() 59 if err != nil { 60 return nil, err 61 } 62 63 // begin validation 64 65 result := &Result{} 66 context := newJsonContext(STRING_CONTEXT_ROOT, nil) 67 v.rootSchema.validateRecursive(v.rootSchema, root, result, context) 68 69 return result, nil 70 71} 72 73func (v *subSchema) subValidateWithContext(document interface{}, context *jsonContext) *Result { 74 result := &Result{} 75 v.validateRecursive(v, document, result, context) 76 return result 77} 78 79// Walker function to validate the json recursively against the subSchema 80func (v *subSchema) validateRecursive(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *jsonContext) { 81 82 if internalLogEnabled { 83 internalLog("validateRecursive %s", context.String()) 84 internalLog(" %v", currentNode) 85 } 86 87 // Handle referenced schemas, returns directly when a $ref is found 88 if currentSubSchema.refSchema != nil { 89 v.validateRecursive(currentSubSchema.refSchema, currentNode, result, context) 90 return 91 } 92 93 // Check for null value 94 if currentNode == nil { 95 if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_NULL) { 96 result.addError( 97 new(InvalidTypeError), 98 context, 99 currentNode, 100 ErrorDetails{ 101 "expected": currentSubSchema.types.String(), 102 "given": TYPE_NULL, 103 }, 104 ) 105 return 106 } 107 108 currentSubSchema.validateSchema(currentSubSchema, currentNode, result, context) 109 v.validateCommon(currentSubSchema, currentNode, result, context) 110 111 } else { // Not a null value 112 113 if isJsonNumber(currentNode) { 114 115 value := currentNode.(json.Number) 116 117 _, isValidInt64, _ := checkJsonNumber(value) 118 119 validType := currentSubSchema.types.Contains(TYPE_NUMBER) || (isValidInt64 && currentSubSchema.types.Contains(TYPE_INTEGER)) 120 121 if currentSubSchema.types.IsTyped() && !validType { 122 123 givenType := TYPE_INTEGER 124 if !isValidInt64 { 125 givenType = TYPE_NUMBER 126 } 127 128 result.addError( 129 new(InvalidTypeError), 130 context, 131 currentNode, 132 ErrorDetails{ 133 "expected": currentSubSchema.types.String(), 134 "given": givenType, 135 }, 136 ) 137 return 138 } 139 140 currentSubSchema.validateSchema(currentSubSchema, value, result, context) 141 v.validateNumber(currentSubSchema, value, result, context) 142 v.validateCommon(currentSubSchema, value, result, context) 143 v.validateString(currentSubSchema, value, result, context) 144 145 } else { 146 147 rValue := reflect.ValueOf(currentNode) 148 rKind := rValue.Kind() 149 150 switch rKind { 151 152 // Slice => JSON array 153 154 case reflect.Slice: 155 156 if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_ARRAY) { 157 result.addError( 158 new(InvalidTypeError), 159 context, 160 currentNode, 161 ErrorDetails{ 162 "expected": currentSubSchema.types.String(), 163 "given": TYPE_ARRAY, 164 }, 165 ) 166 return 167 } 168 169 castCurrentNode := currentNode.([]interface{}) 170 171 currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) 172 173 v.validateArray(currentSubSchema, castCurrentNode, result, context) 174 v.validateCommon(currentSubSchema, castCurrentNode, result, context) 175 176 // Map => JSON object 177 178 case reflect.Map: 179 if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_OBJECT) { 180 result.addError( 181 new(InvalidTypeError), 182 context, 183 currentNode, 184 ErrorDetails{ 185 "expected": currentSubSchema.types.String(), 186 "given": TYPE_OBJECT, 187 }, 188 ) 189 return 190 } 191 192 castCurrentNode, ok := currentNode.(map[string]interface{}) 193 if !ok { 194 castCurrentNode = convertDocumentNode(currentNode).(map[string]interface{}) 195 } 196 197 currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) 198 199 v.validateObject(currentSubSchema, castCurrentNode, result, context) 200 v.validateCommon(currentSubSchema, castCurrentNode, result, context) 201 202 for _, pSchema := range currentSubSchema.propertiesChildren { 203 nextNode, ok := castCurrentNode[pSchema.property] 204 if ok { 205 subContext := newJsonContext(pSchema.property, context) 206 v.validateRecursive(pSchema, nextNode, result, subContext) 207 } 208 } 209 210 // Simple JSON values : string, number, boolean 211 212 case reflect.Bool: 213 214 if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_BOOLEAN) { 215 result.addError( 216 new(InvalidTypeError), 217 context, 218 currentNode, 219 ErrorDetails{ 220 "expected": currentSubSchema.types.String(), 221 "given": TYPE_BOOLEAN, 222 }, 223 ) 224 return 225 } 226 227 value := currentNode.(bool) 228 229 currentSubSchema.validateSchema(currentSubSchema, value, result, context) 230 v.validateNumber(currentSubSchema, value, result, context) 231 v.validateCommon(currentSubSchema, value, result, context) 232 v.validateString(currentSubSchema, value, result, context) 233 234 case reflect.String: 235 236 if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_STRING) { 237 result.addError( 238 new(InvalidTypeError), 239 context, 240 currentNode, 241 ErrorDetails{ 242 "expected": currentSubSchema.types.String(), 243 "given": TYPE_STRING, 244 }, 245 ) 246 return 247 } 248 249 value := currentNode.(string) 250 251 currentSubSchema.validateSchema(currentSubSchema, value, result, context) 252 v.validateNumber(currentSubSchema, value, result, context) 253 v.validateCommon(currentSubSchema, value, result, context) 254 v.validateString(currentSubSchema, value, result, context) 255 256 } 257 258 } 259 260 } 261 262 result.incrementScore() 263} 264 265// Different kinds of validation there, subSchema / common / array / object / string... 266func (v *subSchema) validateSchema(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *jsonContext) { 267 268 if internalLogEnabled { 269 internalLog("validateSchema %s", context.String()) 270 internalLog(" %v", currentNode) 271 } 272 273 if len(currentSubSchema.anyOf) > 0 { 274 275 validatedAnyOf := false 276 var bestValidationResult *Result 277 278 for _, anyOfSchema := range currentSubSchema.anyOf { 279 if !validatedAnyOf { 280 validationResult := anyOfSchema.subValidateWithContext(currentNode, context) 281 validatedAnyOf = validationResult.Valid() 282 283 if !validatedAnyOf && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) { 284 bestValidationResult = validationResult 285 } 286 } 287 } 288 if !validatedAnyOf { 289 290 result.addError(new(NumberAnyOfError), context, currentNode, ErrorDetails{}) 291 292 if bestValidationResult != nil { 293 // add error messages of closest matching subSchema as 294 // that's probably the one the user was trying to match 295 result.mergeErrors(bestValidationResult) 296 } 297 } 298 } 299 300 if len(currentSubSchema.oneOf) > 0 { 301 302 nbValidated := 0 303 var bestValidationResult *Result 304 305 for _, oneOfSchema := range currentSubSchema.oneOf { 306 validationResult := oneOfSchema.subValidateWithContext(currentNode, context) 307 if validationResult.Valid() { 308 nbValidated++ 309 } else if nbValidated == 0 && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) { 310 bestValidationResult = validationResult 311 } 312 } 313 314 if nbValidated != 1 { 315 316 result.addError(new(NumberOneOfError), context, currentNode, ErrorDetails{}) 317 318 if nbValidated == 0 { 319 // add error messages of closest matching subSchema as 320 // that's probably the one the user was trying to match 321 result.mergeErrors(bestValidationResult) 322 } 323 } 324 325 } 326 327 if len(currentSubSchema.allOf) > 0 { 328 nbValidated := 0 329 330 for _, allOfSchema := range currentSubSchema.allOf { 331 validationResult := allOfSchema.subValidateWithContext(currentNode, context) 332 if validationResult.Valid() { 333 nbValidated++ 334 } 335 result.mergeErrors(validationResult) 336 } 337 338 if nbValidated != len(currentSubSchema.allOf) { 339 result.addError(new(NumberAllOfError), context, currentNode, ErrorDetails{}) 340 } 341 } 342 343 if currentSubSchema.not != nil { 344 validationResult := currentSubSchema.not.subValidateWithContext(currentNode, context) 345 if validationResult.Valid() { 346 result.addError(new(NumberNotError), context, currentNode, ErrorDetails{}) 347 } 348 } 349 350 if currentSubSchema.dependencies != nil && len(currentSubSchema.dependencies) > 0 { 351 if isKind(currentNode, reflect.Map) { 352 for elementKey := range currentNode.(map[string]interface{}) { 353 if dependency, ok := currentSubSchema.dependencies[elementKey]; ok { 354 switch dependency := dependency.(type) { 355 356 case []string: 357 for _, dependOnKey := range dependency { 358 if _, dependencyResolved := currentNode.(map[string]interface{})[dependOnKey]; !dependencyResolved { 359 result.addError( 360 new(MissingDependencyError), 361 context, 362 currentNode, 363 ErrorDetails{"dependency": dependOnKey}, 364 ) 365 } 366 } 367 368 case *subSchema: 369 dependency.validateRecursive(dependency, currentNode, result, context) 370 371 } 372 } 373 } 374 } 375 } 376 377 result.incrementScore() 378} 379 380func (v *subSchema) validateCommon(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) { 381 382 if internalLogEnabled { 383 internalLog("validateCommon %s", context.String()) 384 internalLog(" %v", value) 385 } 386 387 // enum: 388 if len(currentSubSchema.enum) > 0 { 389 has, err := currentSubSchema.ContainsEnum(value) 390 if err != nil { 391 result.addError(new(InternalError), context, value, ErrorDetails{"error": err}) 392 } 393 if !has { 394 result.addError( 395 new(EnumError), 396 context, 397 value, 398 ErrorDetails{ 399 "allowed": strings.Join(currentSubSchema.enum, ", "), 400 }, 401 ) 402 } 403 } 404 405 result.incrementScore() 406} 407 408func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface{}, result *Result, context *jsonContext) { 409 410 if internalLogEnabled { 411 internalLog("validateArray %s", context.String()) 412 internalLog(" %v", value) 413 } 414 415 nbValues := len(value) 416 417 // TODO explain 418 if currentSubSchema.itemsChildrenIsSingleSchema { 419 for i := range value { 420 subContext := newJsonContext(strconv.Itoa(i), context) 421 validationResult := currentSubSchema.itemsChildren[0].subValidateWithContext(value[i], subContext) 422 result.mergeErrors(validationResult) 423 } 424 } else { 425 if currentSubSchema.itemsChildren != nil && len(currentSubSchema.itemsChildren) > 0 { 426 427 nbItems := len(currentSubSchema.itemsChildren) 428 429 // while we have both schemas and values, check them against each other 430 for i := 0; i != nbItems && i != nbValues; i++ { 431 subContext := newJsonContext(strconv.Itoa(i), context) 432 validationResult := currentSubSchema.itemsChildren[i].subValidateWithContext(value[i], subContext) 433 result.mergeErrors(validationResult) 434 } 435 436 if nbItems < nbValues { 437 // we have less schemas than elements in the instance array, 438 // but that might be ok if "additionalItems" is specified. 439 440 switch currentSubSchema.additionalItems.(type) { 441 case bool: 442 if !currentSubSchema.additionalItems.(bool) { 443 result.addError(new(ArrayNoAdditionalItemsError), context, value, ErrorDetails{}) 444 } 445 case *subSchema: 446 additionalItemSchema := currentSubSchema.additionalItems.(*subSchema) 447 for i := nbItems; i != nbValues; i++ { 448 subContext := newJsonContext(strconv.Itoa(i), context) 449 validationResult := additionalItemSchema.subValidateWithContext(value[i], subContext) 450 result.mergeErrors(validationResult) 451 } 452 } 453 } 454 } 455 } 456 457 // minItems & maxItems 458 if currentSubSchema.minItems != nil { 459 if nbValues < int(*currentSubSchema.minItems) { 460 result.addError( 461 new(ArrayMinItemsError), 462 context, 463 value, 464 ErrorDetails{"min": *currentSubSchema.minItems}, 465 ) 466 } 467 } 468 if currentSubSchema.maxItems != nil { 469 if nbValues > int(*currentSubSchema.maxItems) { 470 result.addError( 471 new(ArrayMaxItemsError), 472 context, 473 value, 474 ErrorDetails{"max": *currentSubSchema.maxItems}, 475 ) 476 } 477 } 478 479 // uniqueItems: 480 if currentSubSchema.uniqueItems { 481 var stringifiedItems []string 482 for _, v := range value { 483 vString, err := marshalToJsonString(v) 484 if err != nil { 485 result.addError(new(InternalError), context, value, ErrorDetails{"err": err}) 486 } 487 if isStringInSlice(stringifiedItems, *vString) { 488 result.addError( 489 new(ItemsMustBeUniqueError), 490 context, 491 value, 492 ErrorDetails{"type": TYPE_ARRAY}, 493 ) 494 } 495 stringifiedItems = append(stringifiedItems, *vString) 496 } 497 } 498 499 result.incrementScore() 500} 501 502func (v *subSchema) validateObject(currentSubSchema *subSchema, value map[string]interface{}, result *Result, context *jsonContext) { 503 504 if internalLogEnabled { 505 internalLog("validateObject %s", context.String()) 506 internalLog(" %v", value) 507 } 508 509 // minProperties & maxProperties: 510 if currentSubSchema.minProperties != nil { 511 if len(value) < int(*currentSubSchema.minProperties) { 512 result.addError( 513 new(ArrayMinPropertiesError), 514 context, 515 value, 516 ErrorDetails{"min": *currentSubSchema.minProperties}, 517 ) 518 } 519 } 520 if currentSubSchema.maxProperties != nil { 521 if len(value) > int(*currentSubSchema.maxProperties) { 522 result.addError( 523 new(ArrayMaxPropertiesError), 524 context, 525 value, 526 ErrorDetails{"max": *currentSubSchema.maxProperties}, 527 ) 528 } 529 } 530 531 // required: 532 for _, requiredProperty := range currentSubSchema.required { 533 _, ok := value[requiredProperty] 534 if ok { 535 result.incrementScore() 536 } else { 537 result.addError( 538 new(RequiredError), 539 context, 540 value, 541 ErrorDetails{"property": requiredProperty}, 542 ) 543 } 544 } 545 546 // additionalProperty & patternProperty: 547 if currentSubSchema.additionalProperties != nil { 548 549 switch currentSubSchema.additionalProperties.(type) { 550 case bool: 551 552 if !currentSubSchema.additionalProperties.(bool) { 553 554 for pk := range value { 555 556 found := false 557 for _, spValue := range currentSubSchema.propertiesChildren { 558 if pk == spValue.property { 559 found = true 560 } 561 } 562 563 pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context) 564 565 if found { 566 567 if pp_has && !pp_match { 568 result.addError( 569 new(AdditionalPropertyNotAllowedError), 570 context, 571 value, 572 ErrorDetails{"property": pk}, 573 ) 574 } 575 576 } else { 577 578 if !pp_has || !pp_match { 579 result.addError( 580 new(AdditionalPropertyNotAllowedError), 581 context, 582 value, 583 ErrorDetails{"property": pk}, 584 ) 585 } 586 587 } 588 } 589 } 590 591 case *subSchema: 592 593 additionalPropertiesSchema := currentSubSchema.additionalProperties.(*subSchema) 594 for pk := range value { 595 596 found := false 597 for _, spValue := range currentSubSchema.propertiesChildren { 598 if pk == spValue.property { 599 found = true 600 } 601 } 602 603 pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context) 604 605 if found { 606 607 if pp_has && !pp_match { 608 validationResult := additionalPropertiesSchema.subValidateWithContext(value[pk], context) 609 result.mergeErrors(validationResult) 610 } 611 612 } else { 613 614 if !pp_has || !pp_match { 615 validationResult := additionalPropertiesSchema.subValidateWithContext(value[pk], context) 616 result.mergeErrors(validationResult) 617 } 618 619 } 620 621 } 622 } 623 } else { 624 625 for pk := range value { 626 627 pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context) 628 629 if pp_has && !pp_match { 630 631 result.addError( 632 new(InvalidPropertyPatternError), 633 context, 634 value, 635 ErrorDetails{ 636 "property": pk, 637 "pattern": currentSubSchema.PatternPropertiesString(), 638 }, 639 ) 640 } 641 642 } 643 } 644 645 result.incrementScore() 646} 647 648func (v *subSchema) validatePatternProperty(currentSubSchema *subSchema, key string, value interface{}, result *Result, context *jsonContext) (has bool, matched bool) { 649 650 if internalLogEnabled { 651 internalLog("validatePatternProperty %s", context.String()) 652 internalLog(" %s %v", key, value) 653 } 654 655 has = false 656 657 validatedkey := false 658 659 for pk, pv := range currentSubSchema.patternProperties { 660 if matches, _ := regexp.MatchString(pk, key); matches { 661 has = true 662 subContext := newJsonContext(key, context) 663 validationResult := pv.subValidateWithContext(value, subContext) 664 result.mergeErrors(validationResult) 665 if validationResult.Valid() { 666 validatedkey = true 667 } 668 } 669 } 670 671 if !validatedkey { 672 return has, false 673 } 674 675 result.incrementScore() 676 677 return has, true 678} 679 680func (v *subSchema) validateString(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) { 681 682 // Ignore JSON numbers 683 if isJsonNumber(value) { 684 return 685 } 686 687 // Ignore non strings 688 if !isKind(value, reflect.String) { 689 return 690 } 691 692 if internalLogEnabled { 693 internalLog("validateString %s", context.String()) 694 internalLog(" %v", value) 695 } 696 697 stringValue := value.(string) 698 699 // minLength & maxLength: 700 if currentSubSchema.minLength != nil { 701 if utf8.RuneCount([]byte(stringValue)) < int(*currentSubSchema.minLength) { 702 result.addError( 703 new(StringLengthGTEError), 704 context, 705 value, 706 ErrorDetails{"min": *currentSubSchema.minLength}, 707 ) 708 } 709 } 710 if currentSubSchema.maxLength != nil { 711 if utf8.RuneCount([]byte(stringValue)) > int(*currentSubSchema.maxLength) { 712 result.addError( 713 new(StringLengthLTEError), 714 context, 715 value, 716 ErrorDetails{"max": *currentSubSchema.maxLength}, 717 ) 718 } 719 } 720 721 // pattern: 722 if currentSubSchema.pattern != nil { 723 if !currentSubSchema.pattern.MatchString(stringValue) { 724 result.addError( 725 new(DoesNotMatchPatternError), 726 context, 727 value, 728 ErrorDetails{"pattern": currentSubSchema.pattern}, 729 ) 730 731 } 732 } 733 734 // format 735 if currentSubSchema.format != "" { 736 if !FormatCheckers.IsFormat(currentSubSchema.format, stringValue) { 737 result.addError( 738 new(DoesNotMatchFormatError), 739 context, 740 value, 741 ErrorDetails{"format": currentSubSchema.format}, 742 ) 743 } 744 } 745 746 result.incrementScore() 747} 748 749func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) { 750 751 // Ignore non numbers 752 if !isJsonNumber(value) { 753 return 754 } 755 756 if internalLogEnabled { 757 internalLog("validateNumber %s", context.String()) 758 internalLog(" %v", value) 759 } 760 761 number := value.(json.Number) 762 float64Value, _ := number.Float64() 763 764 // multipleOf: 765 if currentSubSchema.multipleOf != nil { 766 767 if !isFloat64AnInteger(float64Value / *currentSubSchema.multipleOf) { 768 result.addError( 769 new(MultipleOfError), 770 context, 771 resultErrorFormatJsonNumber(number), 772 ErrorDetails{"multiple": *currentSubSchema.multipleOf}, 773 ) 774 } 775 } 776 777 //maximum & exclusiveMaximum: 778 if currentSubSchema.maximum != nil { 779 if currentSubSchema.exclusiveMaximum { 780 if float64Value >= *currentSubSchema.maximum { 781 result.addError( 782 new(NumberLTError), 783 context, 784 resultErrorFormatJsonNumber(number), 785 ErrorDetails{ 786 "max": resultErrorFormatNumber(*currentSubSchema.maximum), 787 }, 788 ) 789 } 790 } else { 791 if float64Value > *currentSubSchema.maximum { 792 result.addError( 793 new(NumberLTEError), 794 context, 795 resultErrorFormatJsonNumber(number), 796 ErrorDetails{ 797 "max": resultErrorFormatNumber(*currentSubSchema.maximum), 798 }, 799 ) 800 } 801 } 802 } 803 804 //minimum & exclusiveMinimum: 805 if currentSubSchema.minimum != nil { 806 if currentSubSchema.exclusiveMinimum { 807 if float64Value <= *currentSubSchema.minimum { 808 result.addError( 809 new(NumberGTError), 810 context, 811 resultErrorFormatJsonNumber(number), 812 ErrorDetails{ 813 "min": resultErrorFormatNumber(*currentSubSchema.minimum), 814 }, 815 ) 816 } 817 } else { 818 if float64Value < *currentSubSchema.minimum { 819 result.addError( 820 new(NumberGTEError), 821 context, 822 resultErrorFormatJsonNumber(number), 823 ErrorDetails{ 824 "min": resultErrorFormatNumber(*currentSubSchema.minimum), 825 }, 826 ) 827 } 828 } 829 } 830 831 result.incrementScore() 832} 833