voxpupuli / json-schema

Ruby JSON Schema Validator
MIT License
1.52k stars 242 forks source link

"strict" option does not enforce additionalProperties within array items #412

Open emersonthis opened 5 years ago

emersonthis commented 5 years ago

Sounds related to https://github.com/ruby-json-schema/json-schema/issues/369 or https://github.com/ruby-json-schema/json-schema/issues/404

According to the docs:

#
# with the `:strict` option, all properties are condsidered to have `"required": true` and all objects `"additionalProperties": false`
#

The implied additionalProperties: false does not seem to apply to extra properties in array items/objects.

To reproduce

Fake schema = bugtest.json

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "properties": {
    "an_array" : {
      "properties": {
        "alpha": {
          "type": "string"
        },
        "beta": {
          "type": "string"
        }
      },
      "items": {
        "type": "hash"
      }
      ,"type": "array"
    }

  },
  "type": "object"
}

bugtest_spec.rb

# frozen_string_literal: true

require 'rails_helper'

RSpec.describe 'JSON::Validator "strict" mode', type: :request do

  include SchemaMatchers

  it 'should pass when the properties match exactly' do

    tester = {
      an_array: [
        {
          alpha: 'foo',
          beta: 'foo'
        }
      ]
    }

    schema_path = Rails.root.join('spec', 'support', 'schemas', "bugtest.json")
    valid = JSON::Validator.validate!(schema_path.to_s, tester, { strict: true })

    expect(valid).to eq(true)

  end

  it 'should fail when a property in the schema is missing' do

    tester = {
      an_array: [
        {
          alpha: 'foo',
        }
      ]
    }

    schema_path = Rails.root.join('spec', 'support', 'schemas', "bugtest.json")
    expect{
      JSON::Validator.validate!(schema_path.to_s, tester, { strict: true })
    }.to raise_error(StandardError)

  end

  it 'should fail when an extra property (not in the schema) is present' do

    tester = {
      an_array: [
        {
          alpha: 'foo',
          beta: 'foo',
          gamma: 'foo'
        }
      ]
    }

    schema_path = Rails.root.join('spec', 'support', 'schemas', "bugtest.json")
    expect{
      JSON::Validator.validate!(schema_path.to_s, tester, { strict: true })
    }.to raise_error(StandardError)

  end
end

Expected behavior

All three tests should pass, with validate() returning the expected results.

Actual behavior

The second two examples fail, even with extra or missing properties that don't match the schema. validate does not return false and validate! does not raise an error.

Details

rspec v3.7 ruby 2.3.0p0 json-schema 2.7.0