brandur / json_schema

A JSON Schema V4 and Hyperschema V4 parser and validator.
MIT License
230 stars 45 forks source link

schema.expand_references! doesn't support external URI's #46

Closed kipcole9 closed 10 months ago

kipcole9 commented 8 years ago

Liking this gem a lot for testing, and possibility client api support but .... only supporting schema-relative URI's in $ref's seems to a limitation not defined by the spec. Since my schema passes validation with external URI's then I guess its valid to use them?

Anyway, would be great if json_schema wasn't so restrictive in its $ref dereferencing.

panSarin commented 8 years ago

Hey, i also have problems with $ref. Not sure if the same but i will describe it there instead of opening new issue.

I have big hyper-schema JSON generated from few smaller with PRMD gem (thx. @geemus). It uses $ref to defintions from the same lvl of JSON, but also from diffrent lvls of JSON Schema and diffrent hyperschemas objects. It works, it generate beauty MD file. Then i use big api.json file to select my definition of response that i will validate with json_schema gem like that:

Spec::Matchers.define :match_response_schema do |resource_name, schema_def_name|
  match do |response|
    schema_path = "#{Dir.pwd}/schema/api.json"
    schema_data = JSON.parse(File.read(schema_path))['definitions'][resource_name]['definitions'][schema_def_name]

    schema = JsonSchema.parse! schema_data
    schema.expand_references!
    schema.validate!(response)
  end
end

expand_references! will throw me errors about it cant find my pointers URI. Probably because to schema_data I only pass that part of my JSON that is about my response (it have $ref inside, and it refers to the definitons from parts that i shouldn't pass - at least i think so) . How can I handle expanding references? Maybe i can pass whole JSON first, expand references and then select only part that will be used to make validation ?

Great gem btw!

brandur commented 8 years ago

Hey guys, thanks for the comments! First of all, would you mind checking out #22 and see if it helps your problem at all?

The basic idea here is that the gem doesn't try to dereference complex $refs automatically because it could potentially be dangerous to performance if unexpected dereferences occurred. For example, if a schema contained a URI without a user knowing it, we don't want the library going out to fetch the schema located there because that would be a very unexpectedly slow process. Instead, we use JsonSchema::DocumentStore to house any schemas that we know we need beforehand, and the validator should be able to find them based on how they identify themselves. Does that make sense?