tlivings / enjoi

Converts a JSON schema to a Joi schema.
Apache License 2.0
282 stars 56 forks source link

[Bug] anyOf does not mark field as required #68

Open rmehner opened 5 years ago

rmehner commented 5 years ago

Hey there,

thanks for this useful lib, we hope to use it in our system very soon, however we ran into this bug:

Given the following schema:

{
  "type": "object",
  "properties": {
    "one": { "type": "number", "minimum": 0, "maximum": 10 },
    "two": { "type": "number", "minimum": 0, "maximum": 10 }
  },
  "anyOf": [
    { "required": ["one"] },
    { "required": ["two"] }
  ],
  "additionalProperties": false
}

When I run this code:

const enjoiSchema = Enjoi.schema(jsonSchema)
console.log(Joi.validate({}, enjoiSchema).error === null)

I'd expect this to be false, however it returns true. If I take the same schema and run it through ajv or jsonschema, I get the expected results, so I don't think there's anything wrong with the schema.

If I write the same schema directly in Joi, like this:

Joi.object()
  .keys({
    one: Joi.number().positive().min(0).max(10),
    two: Joi.number().positive().min(0).max(10)
  })
  .or('one', 'two')

it also works as expected and does not see the empty object as valid.

Thanks again for building Enjoi, we hope to enjoy it very soon ;-)

tlivings commented 5 years ago

Thanks, looking into this.

maldimirov commented 5 years ago

anyOf and type are two different validation keywords. I don't think you can use two validation keywords alongside in the same schema. At least I don't see that allowed in the spec. The other option is for anyOf to be a validation keyword for the object type, but that is also not the case sec. 6.5.

I don't think what you described is the expected behavior.

rmehner commented 5 years ago

@maldimirov Thanks for looking into this. If I understand you right, you're saying that my schema is not valid per spec?

If so, both jsonschema and ajv behave not according to spec, as I've mentioned above. But it would explain why enjoi can't deal with it.

maldimirov commented 5 years ago

Yes, I think the schema is not valid. And I don't know why jsonschema and ajv would behave like that. I would speculate that their code does not stop execution on the first occurrence of a validation keyword, but goes on and so executes several validations on the same data because there are several validation keywords in the schema. But even that would not explain this behavior, since from the anyOf spec (sec. 6.7.2):

Each item of the array MUST be a valid JSON Schema

And in your example that is not true.

* This is my understanding of the spec and I may be wrong.

** If I understand correctly your case, you should be able to just use minProperties.