From 7dffcc3327907494dd7d52f584f65f53dfdb6414 Mon Sep 17 00:00:00 2001 From: Eric Proulx Date: Sat, 21 Nov 2026 19:12:09 +0100 Subject: [PATCH] Report a required param the request left out as missing only Every validator of a `requires` param was called whether the request sent the param or not, because PresenceValidator has to be called for a missing one to report it. A custom validator that read the value was then handed nil and raised, so the request answered 500 instead of 400. The README's own AlphaNumeric example does that: requires :text, alpha_numeric: true GET / Before: 500 NoMethodError (undefined method 'match?' for nil) After: 400 text is missing The built-in validators added a second error to `is missing` instead: `n is missing, n does not have a valid value` from `values`, `email is missing, email is empty` from `allow_blank: false`, and `ids is missing, ids is invalid` from a `coerce_with` method handed nil. Only PresenceValidator is now called for an attribute the params do not hold. Every other validator sees only the params a request sent, as it already did for an `optional` param, so a missing one is reported once. Each validator settles this when it is built, so the attribute loop reads an ivar where it called `required?`. A param sent as `null` is still validated, and `values` still rejects it. Asking the params whether they hold each required attribute cost a nested body of 20 items 5%, and `declared` 4%, in Duel. The built-in validators no longer ask again whether the params are a Hash that holds the attribute, as they are now only called when it does. And CoerceValidator, which every typed param has, is still called for a required attribute and tells a missing one for itself, from the value it reads anyway: only a nil is looked up. Every benchmark now measures the same as master. UPGRADING notes the dropped second messages, including the one #3010 documented for a nested param with `values`. The README says when `validate_param!` is called. Fixes #1693. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + README.md | 2 + UPGRADING.md | 22 +++++++ .../validators/allow_blank_validator.rb | 2 +- lib/grape/validations/validators/base.rb | 23 ++++++-- .../validators/coerce_validator.rb | 24 +++++++- .../validators/except_values_validator.rb | 2 - .../validators/length_validator.rb | 2 - .../validations/validators/oneof_validator.rb | 2 - .../validators/presence_validator.rb | 6 ++ .../validators/regexp_validator.rb | 2 - .../validators/same_as_validator.rb | 1 - .../validators/values_validator.rb | 2 - spec/grape/validations/params_scope_spec.rb | 2 +- .../validators/coerce_validator_spec.rb | 31 ++++++++++ .../validators/oneof_validator_spec.rb | 4 +- .../validators/presence_validator_spec.rb | 4 +- .../validators/regexp_validator_spec.rb | 2 +- .../validators/same_as_validator_spec.rb | 8 +++ .../validators/values_validator_spec.rb | 4 +- spec/grape/validations_spec.rb | 58 +++++++++++++++++-- 21 files changed, 174 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad3ef5cf7..b26a46339 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index 5cc412345..efe090e8e 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/UPGRADING.md b/UPGRADING.md index becc35091..0cfb75e99 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -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)`. diff --git a/lib/grape/validations/validators/allow_blank_validator.rb b/lib/grape/validations/validators/allow_blank_validator.rb index 169979986..bab070013 100644 --- a/lib/grape/validations/validators/allow_blank_validator.rb +++ b/lib/grape/validations/validators/allow_blank_validator.rb @@ -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) diff --git a/lib/grape/validations/validators/base.rb b/lib/grape/validations/validators/base.rb index e20a94fa0..a04397c96 100644 --- a/lib/grape/validations/validators/base.rb +++ b/lib/grape/validations/validators/base.rb @@ -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 @@ -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!. @@ -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 @@ -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 diff --git a/lib/grape/validations/validators/coerce_validator.rb b/lib/grape/validations/validators/coerce_validator.rb index 389adcc48..3a2a56abb 100644 --- a/lib/grape/validations/validators/coerce_validator.rb +++ b/lib/grape/validations/validators/coerce_validator.rb @@ -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 @@ -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) diff --git a/lib/grape/validations/validators/except_values_validator.rb b/lib/grape/validations/validators/except_values_validator.rb index 8b34a60b1..089daef70 100644 --- a/lib/grape/validations/validators/except_values_validator.rb +++ b/lib/grape/validations/validators/except_values_validator.rb @@ -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? diff --git a/lib/grape/validations/validators/length_validator.rb b/lib/grape/validations/validators/length_validator.rb index 692901896..e3bff44c0 100644 --- a/lib/grape/validations/validators/length_validator.rb +++ b/lib/grape/validations/validators/length_validator.rb @@ -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) diff --git a/lib/grape/validations/validators/oneof_validator.rb b/lib/grape/validations/validators/oneof_validator.rb index 0b3891cff..885f11466 100644 --- a/lib/grape/validations/validators/oneof_validator.rb +++ b/lib/grape/validations/validators/oneof_validator.rb @@ -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? diff --git a/lib/grape/validations/validators/presence_validator.rb b/lib/grape/validations/validators/presence_validator.rb index 9cb301e32..8691f66a7 100644 --- a/lib/grape/validations/validators/presence_validator.rb +++ b/lib/grape/validations/validators/presence_validator.rb @@ -11,6 +11,12 @@ def validate_param!(attr_name, params) validation_error!(attr_name) end + + private + + def validates_missing? + true + end end end end diff --git a/lib/grape/validations/validators/regexp_validator.rb b/lib/grape/validations/validators/regexp_validator.rb index 53c9da0db..0f8d8fd59 100644 --- a/lib/grape/validations/validators/regexp_validator.rb +++ b/lib/grape/validations/validators/regexp_validator.rb @@ -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) diff --git a/lib/grape/validations/validators/same_as_validator.rb b/lib/grape/validations/validators/same_as_validator.rb index 02fe91d4d..fd72fa0b0 100644 --- a/lib/grape/validations/validators/same_as_validator.rb +++ b/lib/grape/validations/validators/same_as_validator.rb @@ -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) }) diff --git a/lib/grape/validations/validators/values_validator.rb b/lib/grape/validations/validators/values_validator.rb index 1f9738dce..8e0dbb240 100644 --- a/lib/grape/validations/validators/values_validator.rb +++ b/lib/grape/validations/validators/values_validator.rb @@ -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? diff --git a/spec/grape/validations/params_scope_spec.rb b/spec/grape/validations/params_scope_spec.rb index 1c7d225b4..d7f19c47d 100644 --- a/spec/grape/validations/params_scope_spec.rb +++ b/spec/grape/validations/params_scope_spec.rb @@ -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 diff --git a/spec/grape/validations/validators/coerce_validator_spec.rb b/spec/grape/validations/validators/coerce_validator_spec.rb index af61dd02b..ebff4976b 100644 --- a/spec/grape/validations/validators/coerce_validator_spec.rb +++ b/spec/grape/validations/validators/coerce_validator_spec.rb @@ -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 diff --git a/spec/grape/validations/validators/oneof_validator_spec.rb b/spec/grape/validations/validators/oneof_validator_spec.rb index aaa233d38..3045fd913 100644 --- a/spec/grape/validations/validators/oneof_validator_spec.rb +++ b/spec/grape/validations/validators/oneof_validator_spec.rb @@ -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 @@ -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 diff --git a/spec/grape/validations/validators/presence_validator_spec.rb b/spec/grape/validations/validators/presence_validator_spec.rb index 3dc2dc8a8..75c477247 100644 --- a/spec/grape/validations/validators/presence_validator_spec.rb +++ b/spec/grape/validations/validators/presence_validator_spec.rb @@ -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 @@ -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 diff --git a/spec/grape/validations/validators/regexp_validator_spec.rb b/spec/grape/validations/validators/regexp_validator_spec.rb index 1976f289c..0924e5ec3 100644 --- a/spec/grape/validations/validators/regexp_validator_spec.rb +++ b/spec/grape/validations/validators/regexp_validator_spec.rb @@ -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 diff --git a/spec/grape/validations/validators/same_as_validator_spec.rb b/spec/grape/validations/validators/same_as_validator_spec.rb index b4625024f..f11b58beb 100644 --- a/spec/grape/validations/validators/same_as_validator_spec.rb +++ b/spec/grape/validations/validators/same_as_validator_spec.rb @@ -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 diff --git a/spec/grape/validations/validators/values_validator_spec.rb b/spec/grape/validations/validators/values_validator_spec.rb index 7065db2b3..c5cb31a28 100644 --- a/spec/grape/validations/validators/values_validator_spec.rb +++ b/spec/grape/validations/validators/values_validator_spec.rb @@ -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 @@ -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 diff --git a/spec/grape/validations_spec.rb b/spec/grape/validations_spec.rb index a69d06568..cf1d52ffa 100644 --- a/spec/grape/validations_spec.rb +++ b/spec/grape/validations_spec.rb @@ -614,7 +614,7 @@ def define_requires_none it 'errors when param is not a Hash' do get '/required', items: 'not a hash' expect(last_response.status).to eq(400) - expect(last_response.body).to eq('items is invalid, items[key] is missing, items[key] is invalid') + expect(last_response.body).to eq('items is invalid, items[key] is missing') get '/required', items: [{ key: 'hash in array' }] expect(last_response.status).to eq(400) @@ -815,7 +815,7 @@ def validate_param!(attr_name, params) # should actually return 200, since an empty array is valid. get '/within_array', children: [] expect(last_response.status).to eq(400) - expect(last_response.body).to eq('children[0][name] is missing, children[0][parents] is missing, children[0][parents] is invalid') + expect(last_response.body).to eq('children[0][name] is missing, children[0][parents] is missing') get '/within_array', children: [{ name: 'Jay' }] expect(last_response.status).to eq(400) @@ -1510,6 +1510,56 @@ def validate_param!(attr_name, params) end end + context 'when a custom validator reads the value of a required param' do + let(:alpha_numeric) do + Class.new(Grape::Validations::Validators::Base) do + def validate_param!(attr_name, params) + return if params[attr_name].match?(/\A[[:alnum:]]+\z/) + + validation_error!(attr_name, 'must consist of alpha-numeric characters') + end + end + end + + before do + stub_const('AlphaNumericValidator', alpha_numeric) + described_class.register(AlphaNumericValidator) + subject.params do + requires :text, alpha_numeric: true + optional :items, type: Array do + requires :code, alpha_numeric: true + end + end + subject.post('/alpha_numeric') { 'ok' } + end + + after { described_class.deregister(:alpha_numeric) } + + it 'reports the param missing without calling the validator' do + post '/alpha_numeric' + expect(last_response.status).to eq(400) + expect(last_response.body).to eq('text is missing') + end + + it 'reports it missing from an element of an Array without calling the validator' do + post '/alpha_numeric', { text: 'abc', items: [{ code: 'x1' }, { other: 1 }] }.to_json, 'CONTENT_TYPE' => 'application/json' + expect(last_response.status).to eq(400) + expect(last_response.body).to eq('items[1][code] is missing') + end + + it 'reports an element that is not a Hash without calling the validator' do + post '/alpha_numeric', { text: 'abc', items: ['x'] }.to_json, 'CONTENT_TYPE' => 'application/json' + expect(last_response.status).to eq(400) + expect(last_response.body).to eq('items[0] is invalid, items[0][code] is missing') + end + + it 'calls the validator when the param is present' do + post '/alpha_numeric', text: 'a b' + expect(last_response.status).to eq(400) + expect(last_response.body).to eq('text must consist of alpha-numeric characters') + end + end + context 'when using requires with a custom validator' do before do subject.params do @@ -1530,10 +1580,10 @@ def validate_param!(attr_name, params) expect(last_response.body).to eq('required with custom works!') end - it 'validates when param is not present' do + it 'reports a param that is not present as missing, without calling the validator' do get '/required_custom' expect(last_response.status).to eq(400) - expect(last_response.body).to eq('custom is missing, custom is not custom!') + expect(last_response.body).to eq('custom is missing') end context 'nested namespaces' do