Skip to content

Commit

Permalink
fix date string format validation (#130)
Browse files Browse the repository at this point in the history
Quoting from the JSON schema validation vocabulary

> date:  A string instance is valid against this attribute if it is a
>        valid representation according to the "full-date" production.

and from RFC 3339

```
date-fullyear   = 4DIGIT
date-month      = 2DIGIT  ; 01-12
date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on
                            ; month/year
full-date       = date-fullyear "-" date-month "-" date-mday
```

The current implementations allows date strings that don't comply, for
example `"12-12-12"`. The regex based check fixes that.

References:
* OAS 3.0.0 https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#dataTypes
* JSON validation vocabulary https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-7.3
* RFC 3339, section 5.6 https://datatracker.ietf.org/doc/html/rfc3339#section-5.6

Co-authored-by: Nemo Oudeis <dfrey@moneytree.jp>
  • Loading branch information
NemoOudeis and mt-dfrey authored Nov 15, 2024
1 parent c34766c commit f72e3a0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/openapi_parser/schema_validator/string_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ def validate_uuid_format(value, schema)
def validate_date_format(value, schema)
return [value, nil] unless schema.format == 'date'

return [nil, OpenAPIParser::InvalidDateFormat.new(value, schema.object_reference)] unless value =~ /^\d{4}-\d{2}-\d{2}$/

begin
parsed_date = Date.iso8601(value)
rescue ArgumentError
Expand Down
24 changes: 23 additions & 1 deletion spec/openapi_parser/schema_validator/string_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,29 @@
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"not_date\" is not conformant with date format")
expect(e.message).to end_with("Value: \"#{value}\" is not conformant with date format")
end
end
end
context 'incomplete date string (2 digit year)' do
let(:value) { '12-12-12' }
let(:params) { { 'date_str' => value } }

it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"#{value}\" is not conformant with date format")
end
end
end
context 'invalid date string format (/ separator)' do
let(:value) { '12/12/12' }
let(:params) { { 'date_str' => value } }

it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"#{value}\" is not conformant with date format")
end
end
end
Expand Down

0 comments on commit f72e3a0

Please sign in to comment.