Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
* [#3087](https://github.com/ruby-grape/grape/pull/3087): Let a mounted API `use` the named params of the scope it is mounted in - [@ericproulx](https://github.com/ericproulx).
* [#3093](https://github.com/ruby-grape/grape/pull/3093): Move the endpoint Rack stack building into `Endpoint::RackStack` to fix RuboCop - [@ericproulx](https://github.com/ericproulx).
* [#3099](https://github.com/ruby-grape/grape/pull/3099): Report a nested Array scope that got no Array under its own name only - [@ericproulx](https://github.com/ericproulx).
* [#3100](https://github.com/ruby-grape/grape/pull/3100): Report a required param the request left out as missing only - [@ericproulx](https://github.com/ericproulx).
* [#3102](https://github.com/ruby-grape/grape/pull/3102): Stop reading a setting by its key on an API class, such as `MyAPI.namespace_setting(:key)`, from being recorded and discarding the compiled API - [@ericproulx](https://github.com/ericproulx).
* Your contribution here.

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1865,6 +1865,8 @@ params do
end
```

`validate_param!` is only called for a param the request sent. A `requires` param the request left out is reported as `text is missing`, and none of its other validators are called. A param sent as `null` reaches `validate_param!` as `nil`.

You can also create custom classes that take parameters.

```ruby
Expand Down
22 changes: 22 additions & 0 deletions UPGRADING.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,28 @@ post 'avatar' do
end
```

#### A required param the request left out is only reported missing

A `requires` param the request left out now answers `is missing` and nothing else ([#3100](https://github.com/ruby-grape/grape/pull/3100)). Its other validators, custom ones included, are only called for a param the request sent, as they already were for an `optional` one. A custom validator that read the value used to be handed `nil` for it and raise, so the request answered `500` instead of `400`. The README's own `AlphaNumeric` example did that.

The built-in validators that added a second error for a missing param no longer do:

```ruby
params do
requires :n, type: Integer, values: [1, 2]
requires :email, type: String, allow_blank: false
end
```

```
# Before
n is missing, n does not have a valid value, email is missing, email is empty
# After
n is missing, email is missing
```

This also drops the `does not have a valid value` that [#3010](https://github.com/ruby-grape/grape/pull/3010) added after `is missing` for a nested param with `values` (see [A required param with `values` rejects `nil` in a nested scope](#a-required-param-with-values-rejects-nil-in-a-nested-scope)). A param sent as `null` is still validated, and `values` still rejects it. A custom validator that has to see a missing param, to report it in its own words for instance, can override `validate(request)`, which is called whether the param was sent or not.

#### `Grape::Util::MediaType` parses for a vendor's pattern

`Grape::Util::MediaType.parse`, `.best_quality` and `.new` take `vendor_pattern:`, the pattern `Grape::Util::MediaType.vendor_pattern(vendor)` answers, in place of `vendor:` ([#3098](https://github.com/ruby-grape/grape/pull/3098)). The header versioner looks its vendor's pattern up as it is built, so a request no longer reads a cache. Only code calling these internals is affected: pass `vendor_pattern: Grape::Util::MediaType.vendor_pattern(vendor)`.
Expand Down
2 changes: 1 addition & 1 deletion lib/grape/validations/validators/allow_blank_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def initialize(attrs, options, required, scope, opts)
end

def validate_param!(attr_name, params)
return if @value || !hash_like?(params)
return if @value

value = params[attr_name]
return if value == false || !Grape::Util::Scrub.blank?(value)
Expand Down
23 changes: 19 additions & 4 deletions lib/grape/validations/validators/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ def initialize(attrs, options, required, scope, opts)
@opts = SharedOptions.new(**opts.slice(:allow_blank, :fail_fast))
@exception_message = message(self.class.default_message_key) if self.class.default_message_key
@iterator = AttributesIterator.new(@scope).freeze
@validates_missing = validates_missing?
choose_validation_path(scope)
end

Expand Down Expand Up @@ -116,6 +117,19 @@ def validate_param!(attr_name, params)

alias required? required

# Whether #validate_param! is asked about an attribute the params do
# not hold, or params that are not a Hash. PresenceValidator is, to
# report it missing, and CoerceValidator of a required one, which
# tells for itself.
# Every other validator sees only the params a request sent, whether
# they are required or not, so a missing one is reported once, and a
# custom validator is never handed one that is not there. The other
# built-in validators count on it: they read the attribute without
# asking first whether the params are a Hash that holds it.
def validates_missing?
false
end

# A scope's parent, optionality, dependency and type are all set
# before its block declares anything, so these are settled by the
# time a validator is built. See #validate and #validate!.
Expand All @@ -138,7 +152,7 @@ def validate_attributes!(params)
array_errors = nil

@attrs.each do |attr_name|
validate_param!(attr_name, params) if required? || params.key?(attr_name)
validate_param!(attr_name, params) if @validates_missing || params.key?(attr_name)
rescue Grape::Exceptions::Validation => e
(array_errors ||= []) << e
end
Expand Down Expand Up @@ -196,11 +210,12 @@ def validate_iterated!(params)
end

# Runs #validate_param! for each attribute +element+ holds, or for every
# one when they are required, and returns +array_errors+ with what
# failed appended, allocating it on the first failure.
# one when this validator reports a missing one (see
# #validates_missing?), and returns +array_errors+ with what failed
# appended, allocating it on the first failure.
def validate_element_attributes(element, array_errors)
@attrs.each do |attr_name|
validate_param!(attr_name, element) if required? || (hash_like?(element) && element.key?(attr_name))
validate_param!(attr_name, element) if @validates_missing || (hash_like?(element) && element.key?(attr_name))
rescue Grape::Exceptions::Validation => e
(array_errors ||= []) << e
end
Expand Down
24 changes: 22 additions & 2 deletions lib/grape/validations/validators/coerce_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,17 @@ def initialize(attrs, options, required, scope, opts)
# HashWithIndifferentAccess key conversion each time, for every coerced
# attribute of every request.
def validate_param!(attr_name, params)
validation_error!(attr_name) unless hash_like?(params)
return unless hash_like?(params)

value = params[attr_name]
# Left out rather than sent as null, which reads the same. Only a
# +nil+ is looked up, so a param that was sent spares the Hash the
# lookup (see #validates_missing?).
return if value.nil? && !params.key?(attr_name)

new_value = coerce_value(value)

validation_error!(attr_name, new_value.message || exception_message) if new_value.is_a?(Types::InvalidValue)
invalid!(attr_name, new_value) if new_value.is_a?(Types::InvalidValue)

# Don't assign a value if it is identical. It fixes a problem with Hashie::Mash
# which loses wrappers for hashes and arrays after reassigning values
Expand All @@ -49,6 +54,21 @@ def validate_param!(attr_name, params)

private

# Asked about every required attribute, unlike the other validators,
# as it reads each one anyway: every typed param has a coercion, and
# on the elements of an Array the key lookup cost a nested body of 20
# items some 5%. A param left out is still never coerced. An optional
# one is asked about only when it was sent, as a request leaves most
# of those out, and reading one that is not there costs a
# HashWithIndifferentAccess more than asking whether it holds it.
def validates_missing?
required?
end

def invalid!(attr_name, invalid_value)
validation_error!(attr_name, invalid_value.message || exception_message)
end

# Calls the converter built at definition time.
# Custom coercers may raise; any StandardError is treated as an invalid value.
def coerce_value(val)
Expand Down
2 changes: 0 additions & 2 deletions lib/grape/validations/validators/except_values_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ def initialize(attrs, options, required, scope, opts)
end

def validate_param!(attr_name, params)
return unless hash_like?(params) && params.key?(attr_name)

excepts = current_excepts
return if excepts.nil?

Expand Down
2 changes: 0 additions & 2 deletions lib/grape/validations/validators/length_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ def initialize(attrs, options, required, scope, opts)
end

def validate_param!(attr_name, params)
return unless hash_like?(params)

param = params[attr_name]

return unless param.respond_to?(:length)
Expand Down
2 changes: 0 additions & 2 deletions lib/grape/validations/validators/oneof_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ def initialize(attrs, options, required, scope, opts)
end

def validate_param!(attr_name, params)
return unless hash_like?(params)

value = params[attr_name]
return if value.nil? && !required?

Expand Down
6 changes: 6 additions & 0 deletions lib/grape/validations/validators/presence_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ def validate_param!(attr_name, params)

validation_error!(attr_name)
end

private

def validates_missing?
true
end
end
end
end
Expand Down
2 changes: 0 additions & 2 deletions lib/grape/validations/validators/regexp_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ def initialize(attrs, options, required, scope, opts)
end

def validate_param!(attr_name, params)
return unless hash_like?(params) && params.key?(attr_name)

return if Array.wrap(params[attr_name]).all? { |param| param.nil? || scrub(param.to_s).match?(@value) }

validation_error!(attr_name)
Expand Down
1 change: 0 additions & 1 deletion lib/grape/validations/validators/same_as_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ def initialize(attrs, options, required, scope, opts)
end

def validate_param!(attr_name, params)
return unless hash_like?(params)
return if params[attr_name] == params[@value]

validation_error!(attr_name, message { translate(:same_as, parameter: @value) })
Expand Down
2 changes: 0 additions & 2 deletions lib/grape/validations/validators/values_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ def initialize(attrs, options, required, scope, opts)
end

def validate_param!(attr_name, params)
return unless hash_like?(params)

val = scrub(params[attr_name])

return if val.nil? && !required?
Expand Down
2 changes: 1 addition & 1 deletion spec/grape/validations/params_scope_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1065,7 +1065,7 @@ def initialize(value)
post '/lines', { lines: [[{ name: 'x' }]] }.to_json, 'CONTENT_TYPE' => 'application/json'

expect(last_response.status).to eq(400)
expect(last_response.body).to eq('lines[0] is invalid, lines[0][name] is missing, lines[0][name] is invalid')
expect(last_response.body).to eq('lines[0] is invalid, lines[0][name] is missing')
end

it 'rejects elements wrapped in several extra arrays' do
Expand Down
31 changes: 31 additions & 0 deletions spec/grape/validations/validators/coerce_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,37 @@ def self.parse(_val)
end
end

context 'when a required param is left out' do
before do
subject.params do
requires :ids, type: Array[Integer], coerce_with: ->(val) { val.split(',').map(&:to_i) }
requires :tags, type: Set[String]
optional :items, type: Array do
requires :n, type: Integer, coerce_with: ->(val) { Integer(val.strip) }
end
end
subject.post('/') { 'ok' }
end

it 'reports it missing, without coercing it' do
post '/', {}.to_json, 'CONTENT_TYPE' => 'application/json'
expect(last_response.status).to eq(400)
expect(last_response.body).to eq('ids is missing, tags is missing')
end

it 'reports one left out of an element missing, without coercing it' do
post '/', { ids: '1', tags: ['a'], items: [{ n: ' 3' }, {}] }.to_json, 'CONTENT_TYPE' => 'application/json'
expect(last_response.status).to eq(400)
expect(last_response.body).to eq('items[1][n] is missing')
end

it 'coerces one sent as null' do
post '/', { ids: '1', tags: nil }.to_json, 'CONTENT_TYPE' => 'application/json'
expect(last_response.status).to eq(400)
expect(last_response.body).to eq('tags is invalid')
end
end

context 'using coerce_with' do
it 'parses parameters with Array type' do
subject.params do
Expand Down
4 changes: 2 additions & 2 deletions spec/grape/validations/validators/oneof_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@
it 'rejects when the value key is missing entirely' do
post '/pricing', '{}', 'CONTENT_TYPE' => 'application/json'
expect(last_response.status).to eq(400)
expect(JSON.parse(last_response.body)['error']).to include('value is missing')
expect(JSON.parse(last_response.body)['error']).to eq('value is missing')
end
end

Expand Down Expand Up @@ -234,7 +234,7 @@
it 'responds with a validation error instead of raising a TypeError' do
post '/items', { items: ['str'] }.to_json, 'CONTENT_TYPE' => 'application/json'
expect(last_response.status).to eq(400)
expect(JSON.parse(last_response.body)['error']).to include('items[0][value] is invalid')
expect(JSON.parse(last_response.body)['error']).to eq('items[0] is invalid, items[0][value] is missing')
end
end

Expand Down
4 changes: 2 additions & 2 deletions spec/grape/validations/validators/presence_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def app
it 'requires when missing' do
get '/requires'
expect(last_response.status).to eq(400)
expect(last_response.body).to eq('{"error":"email is required, email has no value"}')
expect(last_response.body).to eq('{"error":"email is required"}')
end

it 'requires when empty' do
Expand Down Expand Up @@ -96,7 +96,7 @@ def app
it 'requires when missing' do
get '/'
expect(last_response.status).to eq(400)
expect(last_response.body).to eq('{"error":"email is missing, email is empty"}')
expect(last_response.body).to eq('{"error":"email is missing"}')
end

it 'requires when empty' do
Expand Down
2 changes: 1 addition & 1 deletion spec/grape/validations/validators/regexp_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@
it 'refuses inapppopriate' do
get '/nested_regexp_with_array', people: 'invalid name'
expect(last_response.status).to eq(400)
expect(last_response.body).to eq('{"error":"people is invalid, people[names] is missing, people[names] is invalid"}')
expect(last_response.body).to eq('{"error":"people is invalid, people[names] is missing"}')
end
end

Expand Down
8 changes: 8 additions & 0 deletions spec/grape/validations/validators/same_as_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@
expect(last_response.body).to eq('password_confirmation is not the same as password')
end
end

context 'is left out' do
it 'reports it missing only' do
post '/', password: '987654'
expect(last_response.status).to eq(400)
expect(last_response.body).to eq('password_confirmation is missing')
end
end
end

describe '/value-hash' do
Expand Down
4 changes: 2 additions & 2 deletions spec/grape/validations/validators/values_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ def post_json(path, body)
it 'reports a missing param the way the root scope does' do
post_json '/address', address: {}
expect(last_response.status).to eq 400
expect(last_response.body).to eq({ error: 'address[country] is missing, address[country] does not have a valid value' }.to_json)
expect(last_response.body).to eq({ error: 'address[country] is missing' }.to_json)
end

it 'does not allow nil in a given block whose dependency is met' do
Expand Down Expand Up @@ -1190,7 +1190,7 @@ def app
get 'values_wrapped_by_with_block'

expect(last_response.status).to eq 400
expect(last_response.body).to eq({ error: 'type is missing, type does not have a valid value' }.to_json)
expect(last_response.body).to eq({ error: 'type is missing' }.to_json)
end
end
end
Loading
Loading