xeipuuv / gojsonschema

An implementation of JSON Schema, draft v4 v6 & v7 - Go language
2.55k stars 358 forks source link

Schema validation does not work on enum strings #335

Open felixbecker opened 3 years ago

felixbecker commented 3 years ago

Hi, it seams that the enum validation on string fields does not work as expected.

I have the following example. Schema:

{
    "type": "object",
    "required": [
      "reason"
    ],
    "properties": {

      "reason": {
        "type": "string",
        "enum": ["test1","test2","test3","test4"],
        "$ref": "#/definitions/non-empty-string"
      }
    },
    "definitions": {
      "non-empty-string": {
        "type": "string",
        "minLength": 1
      }
    },
    "additionalProperties": false
  }

Request document

{
    "reason":"other reason"
}

go code:

package main

import (
    _ "embed"
    "fmt"

    "github.com/xeipuuv/gojsonschema"
)

// Schema schema
//go:embed schema.json
var Schema []byte

// Request schema
//go:embed request.json
var Request []byte

func main() {

    schemaLoader := gojsonschema.NewBytesLoader(Schema)

    documentLoader := gojsonschema.NewBytesLoader(Request)

    result, err := gojsonschema.Validate(schemaLoader, documentLoader)

    if err != nil {

        fmt.Println(err)
        panic(err.Error())
    }

    if result.Valid() {
        fmt.Printf("The document is valid\n")
    } else {
        fmt.Printf("The document is not valid. see errors :\n")
        for _, desc := range result.Errors() {
            fmt.Printf("- %s\n", desc)
        }
    }
}

The following program prints the document is valid but it should not be. Testing Schema and Request in the https://www.jsonschemavalidator.net/ the validation fails.

Please advice if I miss something here otherwise I would say this could be a bug.

santhosh-tekuri commented 3 years ago

draft7 says: All other properties in a "$ref" object MUST be ignored

because of this enum is ignored. this behavior is changed later drafts. latest drafts allow to use $ref along with other keywords

as per draft7, the current behavior is correct