From ef943d41355e3c7b835ee53d11b4e89b0e3fedbc Mon Sep 17 00:00:00 2001 From: Robert Mosolgo Date: Mon, 4 Jul 2022 06:28:46 -0400 Subject: [PATCH] Don't allow re-assigning Query#validate after validation --- lib/graphql/query.rb | 11 ++++++++++- lib/graphql/query/validation_pipeline.rb | 4 ++++ spec/graphql/query_spec.rb | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/graphql/query.rb b/lib/graphql/query.rb index 3173371161..aa7c960f87 100644 --- a/lib/graphql/query.rb +++ b/lib/graphql/query.rb @@ -34,7 +34,16 @@ def initialize(name) attr_accessor :operation_name # @return [Boolean] if false, static validation is skipped (execution behavior for invalid queries is undefined) - attr_accessor :validate + attr_reader :validate + + # @param new_validate [Boolean] if false, static validation is skipped. This can't be reasssigned after validation. + def validate=(new_validate) + if defined?(@validation_pipeline) && @validation_pipeline && @validation_pipeline.has_validated? + raise ArgumentError, "Can't reassign Query#validate= after validation has run, remove this assignment." + else + @validate = new_validate + end + end attr_writer :query_string diff --git a/lib/graphql/query/validation_pipeline.rb b/lib/graphql/query/validation_pipeline.rb index e32c91fdb5..2b61bc9a87 100644 --- a/lib/graphql/query/validation_pipeline.rb +++ b/lib/graphql/query/validation_pipeline.rb @@ -45,6 +45,10 @@ def analyzers @query_analyzers end + def has_validated? + @has_validated == true + end + private # If the pipeline wasn't run yet, run it. diff --git a/spec/graphql/query_spec.rb b/spec/graphql/query_spec.rb index d54f5be2d8..0e51e5b423 100644 --- a/spec/graphql/query_spec.rb +++ b/spec/graphql/query_spec.rb @@ -720,6 +720,24 @@ def self.parse_error(err, ctx) assert_equal true, query.valid? assert_equal 0, query.static_errors.length end + + it "can't be reassigned after validating" do + query = GraphQL::Query.new(schema, "{ nonExistingField }") + assert query.fingerprint + query.validate = false + assert_equal true, query.valid? + assert_equal 0, query.static_errors.length + err = assert_raises ArgumentError do + query.validate = true + end + + err2 = assert_raises ArgumentError do + query.validate = false + end + expected_message = "Can't reassign Query#validate= after validation has run, remove this assignment." + assert_equal expected_message, err.message + assert_equal expected_message, err2.message + end end describe "validating with optional arguments and variables: nil" do