Skip to content

Commit

Permalink
Only allow defined formats.
Browse files Browse the repository at this point in the history
We've been accidentally using invalid formats like "timestamp" in some places, so this helps ensure we use formats that will actually have a validation effect.
  • Loading branch information
myronmarston committed Feb 14, 2013
1 parent 5b104d2 commit fbd40f2
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/interpol/endpoint.rb
Expand Up @@ -21,6 +21,32 @@ def data_valid_for_type?(data, type)
end end
end end
end end

# Monkey patch json-schema to only allow the defined formats.
# We've been accidentally using invalid formats like "timestamp",
# so this will help ensure we only use valid ones.
class Validator
VALID_FORMATS = %w[
date-time date time utc-millisec regex color style
phone uri email ip-address ipv6 host-name
]

def open(uri)
return super unless uri.start_with?('file://') && uri.end_with?('draft-03.json')
return StringIO.new(Validator.overriden_draft_03) if Validator.overriden_draft_03

schema = JSON.parse(super.read)
schema.fetch("properties").fetch("format")["enum"] = VALID_FORMATS

override = JSON.dump(schema)
Validator.overriden_draft_03 = override
StringIO.new(override)
end

class << self
attr_accessor :overriden_draft_03
end
end
end end


module Interpol module Interpol
Expand Down
20 changes: 20 additions & 0 deletions spec/unit/interpol/endpoint_spec.rb
Expand Up @@ -323,6 +323,26 @@ def new_with(hash)
}.to raise_error(ValidationError) }.to raise_error(ValidationError)
end end


let(:date_time_string) { "2012-12-12T08:23:12Z" }

it 'rejects unrecognized format options' do
schema['properties']['foo']['type'] = 'string'
schema['properties']['foo']['format'] = 'timestamp' # the valid format is date-time

expect {
subject.validate_data!('foo' => date_time_string)
}.to raise_error(ValidationError, %r|'#/properties/foo/format' value "timestamp"|)
end

it 'allows recognized format options' do
schema['properties']['foo']['type'] = 'string'
schema['properties']['foo']['format'] = 'date-time'

expect {
subject.validate_data!('foo' => date_time_string)
}.not_to raise_error
end

it 'requires all properties' do it 'requires all properties' do
expect { expect {
subject.validate_data!({}) subject.validate_data!({})
Expand Down

0 comments on commit fbd40f2

Please sign in to comment.