diff --git a/googleauth.gemspec b/googleauth.gemspec index c08636fd..2a4ef31b 100755 --- a/googleauth.gemspec +++ b/googleauth.gemspec @@ -26,7 +26,7 @@ Gem::Specification.new do |gem| gem.add_dependency "google-cloud-env", "~> 2.2" gem.add_dependency "google-logging-utils", "~> 0.1" gem.add_dependency "jwt", ">= 1.4", "< 4.0" - gem.add_dependency "multi_json", "~> 1.11" + gem.add_dependency "multi_json", "1.21.0" gem.add_dependency "os", ">= 0.9", "< 2.0" gem.add_dependency "signet", ">= 0.16", "< 2.a" diff --git a/lib/googleauth/client_id.rb b/lib/googleauth/client_id.rb index 7e6c8293..ce775e06 100644 --- a/lib/googleauth/client_id.rb +++ b/lib/googleauth/client_id.rb @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -require "multi_json" +require "googleauth/json_compat" require "googleauth/credentials_loader" require "googleauth/errors" @@ -85,7 +85,7 @@ def self.from_file file raise InitializationError, "File can not be nil." if file.nil? File.open file.to_s do |f| json = f.read - config = MultiJson.load json + config = MultiJSON.parse json from_hash config end end diff --git a/lib/googleauth/credentials.rb b/lib/googleauth/credentials.rb index a6c3033f..03475edc 100644 --- a/lib/googleauth/credentials.rb +++ b/lib/googleauth/credentials.rb @@ -16,7 +16,7 @@ require "json" require "pathname" require "signet/oauth_2/client" -require "multi_json" +require "googleauth/json_compat" require "googleauth/credentials_loader" require "googleauth/errors" @@ -370,7 +370,7 @@ def disable_universe_domain_check # * Any credentials object that supports the methods this wrapper delegates to an inner client. # # If this parameter is an object (`Signet::OAuth2::Client` or other) it will be used as an inner client. - # Otherwise the inner client will be constructed from the JSON keyfile or the contens of the hash. + # Otherwise the inner client will be constructed from the JSON keyfile or the contents of the hash. # # @param [Hash] options # The options for configuring this wrapper credentials object and the inner client. @@ -514,7 +514,7 @@ def self.from_io io, options json_key, clz = Google::Auth::DefaultCredentials.determine_creds_class creds_input[:json_key_io] # Re-serialize the parsed JSON and replace the IO stream in creds_input - creds_input[:json_key_io] = StringIO.new MultiJson.dump(json_key) + creds_input[:json_key_io] = StringIO.new MultiJSON.generate(json_key) client = clz.make_creds creds_input options = options.select { |k, _v| k == :logger } @@ -531,7 +531,7 @@ def self.init_client hash, options = {} json_key, clz = Google::Auth::DefaultCredentials.determine_creds_class io # Re-serialize the parsed JSON and create a new IO stream. - new_io = StringIO.new MultiJson.dump(json_key) + new_io = StringIO.new MultiJSON.generate(json_key) clz.make_creds options.merge!(json_key_io: new_io) end diff --git a/lib/googleauth/credentials_loader.rb b/lib/googleauth/credentials_loader.rb index c66c31fb..acb46235 100644 --- a/lib/googleauth/credentials_loader.rb +++ b/lib/googleauth/credentials_loader.rb @@ -16,6 +16,7 @@ require "rbconfig" require "googleauth/errors" +require "googleauth/json_compat" module Google # Module Auth provides classes that provide Google-specific authorization @@ -152,7 +153,7 @@ def load_gcloud_project_id gcloud = GCLOUD_WINDOWS_COMMAND if OS.windows? gcloud = GCLOUD_POSIX_COMMAND unless OS.windows? gcloud_json = IO.popen("#{gcloud} #{GCLOUD_CONFIG_COMMAND}", err: :close, &:read) - config = MultiJson.load gcloud_json + config = MultiJSON.parse gcloud_json config["configuration"]["properties"]["core"]["project"] rescue StandardError nil @@ -165,7 +166,7 @@ def load_gcloud_project_id # @param expected_type [String] The expected credential type name. # @raise [Google::Auth::InitializationError] If the JSON key type does not match the expected type. def load_and_verify_json_key_type json_key_io, expected_type - json_key = MultiJson.load json_key_io.read + json_key = MultiJSON.parse json_key_io.read json_key_io.rewind # Rewind the stream so it can be read again. return if json_key["type"] == expected_type raise Google::Auth::InitializationError, diff --git a/lib/googleauth/default_credentials.rb b/lib/googleauth/default_credentials.rb index ce722c46..dd3e0118 100644 --- a/lib/googleauth/default_credentials.rb +++ b/lib/googleauth/default_credentials.rb @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -require "multi_json" +require "googleauth/json_compat" require "stringio" require "googleauth/credentials_loader" @@ -81,7 +81,7 @@ def self.make_creds options = {} json_key_io = options[:json_key_io] json_key, clz = determine_creds_class json_key_io if json_key - io = StringIO.new MultiJson.dump(json_key) + io = StringIO.new MultiJSON.generate(json_key) clz.make_creds options.merge(json_key_io: io) else clz.make_creds options @@ -97,7 +97,7 @@ def self.make_creds options = {} # or if the environment variable is undefined or unsupported. def self.determine_creds_class json_key_io = nil if json_key_io - json_key = MultiJson.load json_key_io.read + json_key = MultiJSON.parse json_key_io.read key = "type" raise InitializationError, "the json is missing the '#{key}' field" unless json_key.key? key type = json_key[key] diff --git a/lib/googleauth/external_account.rb b/lib/googleauth/external_account.rb index 88861618..4f4d3d9c 100644 --- a/lib/googleauth/external_account.rb +++ b/lib/googleauth/external_account.rb @@ -62,12 +62,12 @@ def self.make_creds options = {} json_key_io, scope = options.values_at :json_key_io, :scope raise InitializationError, "A json file is required for external account credentials." unless json_key_io - json_key = MultiJson.load json_key_io.read, symbolize_keys: true + json_key = MultiJSON.parse json_key_io.read, symbolize_names: true if json_key.key? :type json_key_io.rewind else # Defaults to class credential 'type' if missing. json_key[:type] = CREDENTIAL_TYPE_NAME - json_key_io = StringIO.new MultiJson.dump(json_key) + json_key_io = StringIO.new MultiJSON.generate(json_key) end CredentialsLoader.load_and_verify_json_key_type json_key_io, CREDENTIAL_TYPE_NAME user_creds = read_json_key json_key_io @@ -86,7 +86,7 @@ def self.make_creds options = {} # @return [Hash] The parsed JSON key # @raise [Google::Auth::InitializationError] If the JSON is missing required fields def self.read_json_key json_key_io - json_key = MultiJson.load json_key_io.read, symbolize_keys: true + json_key = MultiJSON.parse json_key_io.read, symbolize_names: true wanted = [ :audience, :subject_token_type, :token_url, :credential_source ] diff --git a/lib/googleauth/external_account/aws_credentials.rb b/lib/googleauth/external_account/aws_credentials.rb index 510a35cc..4628039a 100644 --- a/lib/googleauth/external_account/aws_credentials.rb +++ b/lib/googleauth/external_account/aws_credentials.rb @@ -226,7 +226,7 @@ def fetch_metadata_role_name # Retrieves the AWS security credentials required for signing AWS requests from the AWS metadata server. def fetch_metadata_security_credentials role_name response = get_aws_resource "#{@credential_verification_url}/#{role_name}", "credentials" - MultiJson.load response.body + MultiJSON.parse response.body end # Reads the name of the AWS region from the environment diff --git a/lib/googleauth/external_account/base_credentials.rb b/lib/googleauth/external_account/base_credentials.rb index a2dceba1..01c2feae 100644 --- a/lib/googleauth/external_account/base_credentials.rb +++ b/lib/googleauth/external_account/base_credentials.rb @@ -190,7 +190,7 @@ def get_impersonated_access_token token, _options = {} response = connection.post @service_account_impersonation_url do |req| req.headers["Authorization"] = "Bearer #{token}" req.headers["Content-Type"] = "application/json" - req.body = MultiJson.dump({ scope: @scope }) + req.body = MultiJSON.generate({ scope: @scope }) end if response.status != 200 @@ -201,7 +201,7 @@ def get_impersonated_access_token token, _options = {} ) end - MultiJson.load response.body + MultiJSON.parse response.body end def log_impersonated_token_request original_token diff --git a/lib/googleauth/external_account/external_account_utils.rb b/lib/googleauth/external_account/external_account_utils.rb index c3ab9cef..11b9b6ac 100644 --- a/lib/googleauth/external_account/external_account_utils.rb +++ b/lib/googleauth/external_account/external_account_utils.rb @@ -54,7 +54,7 @@ def project_id end if response.status == 200 - response_data = MultiJson.load response.body, symbolize_names: true + response_data = MultiJSON.parse response.body, symbolize_names: true @project_id = response_data[:projectId] end diff --git a/lib/googleauth/external_account/identity_pool_credentials.rb b/lib/googleauth/external_account/identity_pool_credentials.rb index 56cef226..a915ce02 100644 --- a/lib/googleauth/external_account/identity_pool_credentials.rb +++ b/lib/googleauth/external_account/identity_pool_credentials.rb @@ -63,7 +63,7 @@ def retrieve_subject_token! token = content else begin - response_data = MultiJson.load content, symbolize_keys: true + response_data = MultiJSON.parse content, symbolize_names: true token = response_data[@credential_source_field_name.to_sym] rescue StandardError raise CredentialsError, "Unable to parse subject_token from JSON resource #{resource_name} " \ diff --git a/lib/googleauth/external_account/pluggable_credentials.rb b/lib/googleauth/external_account/pluggable_credentials.rb index d02f34b0..708fa8be 100644 --- a/lib/googleauth/external_account/pluggable_credentials.rb +++ b/lib/googleauth/external_account/pluggable_credentials.rb @@ -88,7 +88,7 @@ def retrieve_subject_token! env = inject_environment_variables output = subprocess_with_timeout env, @credential_source_executable_command, @credential_source_executable_timeout_millis - response = MultiJson.load output, symbolize_keys: true + response = MultiJSON.parse output, symbolize_names: true parse_subject_token response end @@ -99,7 +99,7 @@ def load_subject_token_from_output_file return nil unless File.exist? @credential_source_executable_output_file begin content = File.read @credential_source_executable_output_file, encoding: "utf-8" - response = MultiJson.load content, symbolize_keys: true + response = MultiJSON.parse content, symbolize_names: true rescue StandardError return nil end diff --git a/lib/googleauth/iam.rb b/lib/googleauth/iam.rb index d51c2f0c..fd8cf0c7 100644 --- a/lib/googleauth/iam.rb +++ b/lib/googleauth/iam.rb @@ -14,7 +14,7 @@ require "googleauth/signet" require "googleauth/credentials_loader" -require "multi_json" +require "googleauth/json_compat" module Google # Module Auth provides classes that provide Google-specific authorization diff --git a/lib/googleauth/impersonated_service_account.rb b/lib/googleauth/impersonated_service_account.rb index b659c4ff..6024ea0f 100644 --- a/lib/googleauth/impersonated_service_account.rb +++ b/lib/googleauth/impersonated_service_account.rb @@ -15,6 +15,7 @@ require "googleauth/base_client" require "googleauth/errors" require "googleauth/helpers/connection" +require "googleauth/json_compat" module Google module Auth @@ -117,7 +118,7 @@ def self.make_creds_from_json options end require "googleauth/default_credentials" - impersonated_json = MultiJson.load json_key_io.read + impersonated_json = MultiJSON.parse json_key_io.read source_credentials_info = impersonated_json["source_credentials"] if source_credentials_info["type"] == CREDENTIAL_TYPE_NAME @@ -127,7 +128,7 @@ def self.make_creds_from_json options end source_credentials = DefaultCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(source_credentials_info)) + json_key_io: StringIO.new(MultiJSON.generate(source_credentials_info)) ) impersonation_url = impersonated_json["service_account_impersonation_url"] @@ -279,7 +280,7 @@ def fetch_access_token! _options = {} case resp.status when 200 - response = MultiJson.load resp.body + response = MultiJSON.parse resp.body self.expires_at = response["expireTime"] @access_token = response["accessToken"] access_token @@ -310,7 +311,7 @@ def make_impersonation_request auth_header connection.post @impersonation_url do |req| req.headers.merge! auth_header req.headers["Content-Type"] = "application/json" - req.body = MultiJson.dump({ scope: @scope }) + req.body = MultiJSON.generate({ scope: @scope }) end end diff --git a/lib/googleauth/json_compat.rb b/lib/googleauth/json_compat.rb new file mode 100644 index 00000000..bd17610d --- /dev/null +++ b/lib/googleauth/json_compat.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +require "multi_json" + +# MultiJSON was introduced as the canonical all-caps constant in multi_json 1.21.0, +# along with parse/generate (replacing load/dump) and symbolize_names: (replacing +# symbolize_keys:). For older versions we define a shim so all call sites can use +# the 1.21+ API uniformly. +# To be removed when we drop support for multi_json < 1.21.0 +unless defined?(::MultiJSON) + module ::MultiJSON # rubocop:disable Style/Documentation + def self.parse str, opts = {} + opts[:symbolize_keys] = opts.delete(:symbolize_names) if opts.key? :symbolize_names + MultiJson.load str, opts + end + + def self.generate obj, opts = {} + MultiJson.dump obj, opts + end + + ParseError = MultiJson::ParseError + end +end diff --git a/lib/googleauth/json_key_reader.rb b/lib/googleauth/json_key_reader.rb index 1c53c47d..31db3ed9 100644 --- a/lib/googleauth/json_key_reader.rb +++ b/lib/googleauth/json_key_reader.rb @@ -13,6 +13,7 @@ # limitations under the License. require "googleauth/errors" +require "googleauth/json_compat" module Google # Module Auth provides classes that provide Google-specific authorization @@ -29,7 +30,7 @@ module JsonKeyReader # @raise [Google::Auth::InitializationError] If client_email or private_key # fields are missing from the JSON def read_json_key json_key_io - json_key = MultiJson.load json_key_io.read + json_key = MultiJSON.parse json_key_io.read raise InitializationError, "missing client_email" unless json_key.key? "client_email" raise InitializationError, "missing private_key" unless json_key.key? "private_key" [ diff --git a/lib/googleauth/oauth2/sts_client.rb b/lib/googleauth/oauth2/sts_client.rb index 133736b2..7b600d01 100644 --- a/lib/googleauth/oauth2/sts_client.rb +++ b/lib/googleauth/oauth2/sts_client.rb @@ -14,6 +14,7 @@ require "googleauth/errors" require "googleauth/helpers/connection" +require "googleauth/json_compat" module Google module Auth @@ -89,7 +90,7 @@ def exchange_token options = {} raise AuthorizationError, "Token exchange failed with status #{response.status}" end - MultiJson.load response.body + MultiJSON.parse response.body end private @@ -104,7 +105,7 @@ def make_request options = {} subject_token_type: options[:subject_token_type] } unless options[:additional_options].nil? - request_body[:options] = CGI.escape MultiJson.dump(options[:additional_options], symbolize_name: true) + request_body[:options] = CGI.escape MultiJSON.generate(options[:additional_options]) end request_body end diff --git a/lib/googleauth/scope_util.rb b/lib/googleauth/scope_util.rb index 46ae218c..8cc72f66 100644 --- a/lib/googleauth/scope_util.rb +++ b/lib/googleauth/scope_util.rb @@ -14,7 +14,7 @@ require "googleauth/signet" require "googleauth/credentials_loader" -require "multi_json" +require "googleauth/json_compat" module Google module Auth diff --git a/lib/googleauth/service_account.rb b/lib/googleauth/service_account.rb index 84a4bfef..5c9be48b 100644 --- a/lib/googleauth/service_account.rb +++ b/lib/googleauth/service_account.rb @@ -13,7 +13,7 @@ # limitations under the License. require "jwt" -require "multi_json" +require "googleauth/json_compat" require "stringio" require "google/logging/message" @@ -66,12 +66,12 @@ def self.make_creds options = {} # rubocop:disable Metrics/MethodLength private_key, client_email, project_id, quota_project_id, universe_domain = if json_key_io - json_key = MultiJson.load json_key_io.read + json_key = MultiJSON.parse json_key_io.read if json_key.key? "type" json_key_io.rewind else # Defaults to class credential 'type' if missing. json_key["type"] = CREDENTIAL_TYPE_NAME - json_key_io = StringIO.new MultiJson.dump(json_key) + json_key_io = StringIO.new MultiJSON.generate(json_key) end CredentialsLoader.load_and_verify_json_key_type json_key_io, CREDENTIAL_TYPE_NAME read_json_key json_key_io diff --git a/lib/googleauth/user_authorizer.rb b/lib/googleauth/user_authorizer.rb index feb9b507..a3b83547 100644 --- a/lib/googleauth/user_authorizer.rb +++ b/lib/googleauth/user_authorizer.rb @@ -13,7 +13,7 @@ # limitations under the License. require "uri" -require "multi_json" +require "googleauth/json_compat" require "googleauth/signet" require "googleauth/user_refresh" require "securerandom" @@ -140,7 +140,7 @@ def get_authorization_url options = {} def get_credentials user_id, scope = nil saved_token = stored_token user_id return nil if saved_token.nil? - data = MultiJson.load saved_token + data = MultiJSON.parse saved_token if data.fetch("client_id", @client_id.id) != @client_id.id raise CredentialsError.with_details( @@ -250,7 +250,7 @@ def revoke_authorization user_id # @return [Google::Auth::UserRefreshCredentials] # The stored credentials def store_credentials user_id, credentials - json = MultiJson.dump( + json = MultiJSON.generate( client_id: credentials.client_id, access_token: credentials.access_token, refresh_token: credentials.refresh_token, diff --git a/lib/googleauth/user_refresh.rb b/lib/googleauth/user_refresh.rb index b3965d27..00797094 100644 --- a/lib/googleauth/user_refresh.rb +++ b/lib/googleauth/user_refresh.rb @@ -16,7 +16,7 @@ require "googleauth/errors" require "googleauth/scope_util" require "googleauth/signet" -require "multi_json" +require "googleauth/json_compat" module Google # Module Auth provides classes that provide Google-specific authorization @@ -50,12 +50,12 @@ class UserRefreshCredentials < Signet::OAuth2::Client def self.make_creds options = {} # rubocop:disable Metrics/MethodLength json_key_io, scope = options.values_at :json_key_io, :scope user_creds = if json_key_io - json_key = MultiJson.load json_key_io.read + json_key = MultiJSON.parse json_key_io.read if json_key.key? "type" json_key_io.rewind else # Defaults to class credential 'type' if missing. json_key["type"] = CREDENTIAL_TYPE_NAME - json_key_io = StringIO.new MultiJson.dump(json_key) + json_key_io = StringIO.new MultiJSON.generate(json_key) end CredentialsLoader.load_and_verify_json_key_type json_key_io, CREDENTIAL_TYPE_NAME read_json_key json_key_io @@ -86,7 +86,7 @@ def self.make_creds options = {} # rubocop:disable Metrics/MethodLength # @return [Hash] The parsed JSON key # @raise [Google::Auth::InitializationError] If the JSON is missing required fields def self.read_json_key json_key_io - json_key = MultiJson.load json_key_io.read + json_key = MultiJSON.parse json_key_io.read wanted = ["client_id", "client_secret", "refresh_token"] wanted.each do |key| raise InitializationError, "the json is missing the #{key} field" unless json_key.key? key diff --git a/lib/googleauth/web_user_authorizer.rb b/lib/googleauth/web_user_authorizer.rb index 9e5cec98..ae9a4ba4 100644 --- a/lib/googleauth/web_user_authorizer.rb +++ b/lib/googleauth/web_user_authorizer.rb @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -require "multi_json" +require "googleauth/json_compat" require "googleauth/errors" require "googleauth/signet" require "googleauth/user_authorizer" @@ -84,7 +84,7 @@ class << self # Redirect URI if successfully extracted, nil otherwise def self.handle_auth_callback_deferred request callback_state, redirect_uri = extract_callback_state request - request.session[CALLBACK_STATE_KEY] = MultiJson.dump callback_state + request.session[CALLBACK_STATE_KEY] = MultiJSON.generate callback_state redirect_uri end @@ -166,10 +166,10 @@ def get_authorization_url options = {} redirect_to = options[:redirect_to] || request.url request.session[XSRF_KEY] = SecureRandom.base64 - options[:state] = MultiJson.dump(state.merge( - SESSION_ID_KEY => request.session[XSRF_KEY], - CURRENT_URI_KEY => redirect_to - )) + options[:state] = MultiJSON.generate(state.merge( + SESSION_ID_KEY => request.session[XSRF_KEY], + CURRENT_URI_KEY => redirect_to + )) options[:base_url] = request.url super options end @@ -194,7 +194,7 @@ def get_credentials user_id, request = nil, scope = nil # Note - in theory, no need to check required scope as this is # expected to be called immediately after a return from authorization state_json = request.session.delete CALLBACK_STATE_KEY - callback_state = MultiJson.load state_json + callback_state = MultiJSON.parse state_json WebUserAuthorizer.validate_callback_state callback_state, request get_and_store_credentials_from_code( user_id: user_id, @@ -214,7 +214,7 @@ def get_credentials user_id, request = nil, scope = nil # @return [Array] # Callback state and redirect URI def self.extract_callback_state request - state = MultiJson.load(request.params[STATE_PARAM] || "{}") + state = MultiJSON.parse(request.params[STATE_PARAM] || "{}") redirect_uri = state[CURRENT_URI_KEY] callback_state = { AUTH_CODE_KEY => request.params[AUTH_CODE_KEY], diff --git a/spec/googleauth/compute_engine_spec.rb b/spec/googleauth/compute_engine_spec.rb index 6a07fdd6..41d89498 100644 --- a/spec/googleauth/compute_engine_spec.rb +++ b/spec/googleauth/compute_engine_spec.rb @@ -48,7 +48,7 @@ def make_auth_stubs opts universe_stub.to_return body: @universe_domain, status: 200, headers: {"Metadata-Flavor" => "Google" } end if opts[:access_token] - body = MultiJson.dump("access_token" => opts[:access_token], + body = MultiJSON.generate("access_token" => opts[:access_token], "token_type" => "Bearer", "expires_in" => 3600) diff --git a/spec/googleauth/credentials_spec.rb b/spec/googleauth/credentials_spec.rb index ff500085..a2b99129 100644 --- a/spec/googleauth/credentials_spec.rb +++ b/spec/googleauth/credentials_spec.rb @@ -44,7 +44,7 @@ def stub_token_request access_token: nil, id_token: nil, uri: nil else body_fields["access_token"] = access_token || "12345abcde" end - body = MultiJson.dump body_fields + body = MultiJSON.generate body_fields uri ||= "https://oauth2.googleapis.com/token" stub_request(:post, uri) .to_return(body: body, status: 200, headers: { "Content-Type" => "application/json" }) @@ -609,7 +609,7 @@ class TestCredentialsPathname < Google::Auth::Credentials File.write keyfile_path_str, default_keyfile_content keyfile_pathname = Pathname.new keyfile_path_str # Create a Pathname object creds = TestCredentialsPathname.new keyfile_pathname, enable_self_signed_jwt: true - + expect(creds.client).to be_a_kind_of(Google::Auth::ServiceAccountCredentials) # Verify that project_id and quota_project_id are loaded correctly from the file via Pathname expect(creds.project_id).to eq(default_keyfile_hash["project_id"]) @@ -631,7 +631,7 @@ def initialize scope = nil, project_id = nil @scope = scope @project_id = project_id end - + def duplicate options = {} new_credentials = self.class.new new_credentials.scope = options[:scope] if options[:scope] @@ -640,17 +640,17 @@ def duplicate options = {} end end end - + before :example do @client = client_class.new @base_creds = Google::Auth::Credentials.new(@client) @creds = @base_creds.duplicate end - + it "should call duplicate and update! on clients when clients support it" do client_with_duplicate = double("ClientWithDuplicate") allow(client_with_duplicate).to receive(:respond_to?).with(:duplicate).and_return(true) - + # These will be called when we create new `Google::Auth::Credentials` in this test method allow(client_with_duplicate).to receive(:respond_to?).with(:project_id).and_return(false) allow(client_with_duplicate).to receive(:respond_to?).with(:quota_project_id).and_return(false) @@ -660,13 +660,13 @@ def duplicate options = {} allow(duplicated_client).to receive(:respond_to?).with(:update!).and_return(true) # These will be called when a new `Google::Auth::Credentials` will be created in the - # process of the `duplicate` call. + # process of the `duplicate` call. # First the `client_with_duplicate` will return `duplicated_client` from its `duplicate` call # Then the new `Google::Auth::Credentials` will be created with the `duplicated_client` allow(duplicated_client).to receive(:respond_to?).with(:project_id).and_return(false) allow(duplicated_client).to receive(:respond_to?).with(:quota_project_id).and_return(false) allow(duplicated_client).to receive(:respond_to?).with(:logger=).and_return(false) - + #expect(duplicated_client).to receive(:update!).and_return(duplicated_client) expect(client_with_duplicate).to receive(:duplicate).and_return(duplicated_client) @@ -676,13 +676,13 @@ def duplicate options = {} new_creds = creds.duplicate(foo: "bar") expect(new_creds.client).to eq duplicated_client end - + it "should duplicate the project_id" do # This should be nil, but for case of local testing expect(@creds.project_id).to eq Google::Auth::CredentialsLoader.load_gcloud_project_id - expect(@creds.duplicate(project_id: "test-project-id").project_id).to eq "test-project-id" + expect(@creds.duplicate(project_id: "test-project-id").project_id).to eq "test-project-id" end - + it "should duplicate the quota_project_id" do expect(@creds.quota_project_id).to be_nil expect(@creds.duplicate(quota_project_id: "test-quota-project-id").quota_project_id).to eq "test-quota-project-id" @@ -703,13 +703,13 @@ def duplicate options = {} client = double("Google::Auth::BaseClientFull") allow(client).to receive(:respond_to?).with(:project_id).and_return(true) allow(client).to receive(:project_id).and_return(client_project_id) - + allow(client).to receive(:respond_to?).with(:quota_project_id).and_return(true) allow(client).to receive(:quota_project_id).and_return(client_quota_project_id) - + allow(client).to receive(:respond_to?).with(:logger).and_return(true) allow(client).to receive(:logger).and_return(client_logger) - + allow(client).to receive(:respond_to?).with(:logger=).and_return(true) allow(client).to receive(:logger=) # Allow it to be called client @@ -719,10 +719,10 @@ def duplicate options = {} client = double("Google::Auth::BaseClientMinimal") allow(client).to receive(:respond_to?).with(:project_id).and_return(false) allow(client).to receive(:respond_to?).with(:quota_project_id).and_return(false) - + allow(client).to receive(:respond_to?).with(:logger).and_return(true) allow(client).to receive(:logger).and_return(nil) - + allow(client).to receive(:respond_to?).with(:logger=).and_return(true) allow(client).to receive(:logger=) client diff --git a/spec/googleauth/external_account/aws_credentials_spec.rb b/spec/googleauth/external_account/aws_credentials_spec.rb index b0d9d2e6..7ea7438d 100644 --- a/spec/googleauth/external_account/aws_credentials_spec.rb +++ b/spec/googleauth/external_account/aws_credentials_spec.rb @@ -139,7 +139,7 @@ let :security_credential_endpoint_success do return unless security_credential_url and aws_metadata_role_name security_credential_endpoint.to_return( - body: MultiJson.dump(aws_security_credentials_response)) + body: MultiJSON.generate(aws_security_credentials_response)) end let :security_credential_endpoint_failure do @@ -197,7 +197,7 @@ def impersonation_endpoint access_token def impersonation_endpoint_success access_token return unless access_token and service_account_impersonation_url impersonation_endpoint(access_token).to_return( - body: MultiJson.dump(google_token_impersonation_response.merge({ + body: MultiJSON.generate(google_token_impersonation_response.merge({ accessToken: access_token })) ) @@ -214,7 +214,7 @@ def google_cred_endpoint def google_cred_endpoint_success access_token google_cred_endpoint.to_return( - body: MultiJson.dump(google_token_response.merge({ + body: MultiJSON.generate(google_token_response.merge({ "access_token" => access_token })) ) diff --git a/spec/googleauth/external_account/identity_pool_credentials_spec.rb b/spec/googleauth/external_account/identity_pool_credentials_spec.rb index 7d9c29b7..80f3395b 100644 --- a/spec/googleauth/external_account/identity_pool_credentials_spec.rb +++ b/spec/googleauth/external_account/identity_pool_credentials_spec.rb @@ -81,7 +81,7 @@ describe "test initialization" do examples = [ { - :name => "from full options", + :name => "from full options", :options => { :audience => AUDIENCE, :subject_token_type => SUBJECT_TOKEN_TYPE, @@ -220,7 +220,7 @@ :credential_source => CREDENTIAL_SOURCE_JSON, }, :file_exists => true, - :file_output => MultiJson.dump(SUCCESS_RESPONSE), + :file_output => MultiJSON.generate(SUCCESS_RESPONSE), :expect_result => "ACCESS_TOKEN", }, { @@ -291,7 +291,7 @@ :token_url => TOKEN_URL, :credential_source => CREDENTIAL_SOURCE_JSON_URL, }, - :url_response => {"status": 200, "body": MultiJson.dump(SUCCESS_RESPONSE)}, + :url_response => {"status": 200, "body": MultiJSON.generate(SUCCESS_RESPONSE)}, :expect_result => "ACCESS_TOKEN", }, { @@ -347,7 +347,7 @@ 'format': {'type': 'json', 'subject_token_field_name': 'access_token'}, }, }, - :url_response => {"status": 200, "body": MultiJson.dump({ + :url_response => {"status": 200, "body": MultiJSON.generate({ 'issued_token_type': 'urn:ietf:params:oauth:token-type:access_token', 'token_type': 'Bearer', 'expires_in': 3600, diff --git a/spec/googleauth/external_account/pluggable_credentials_spec.rb b/spec/googleauth/external_account/pluggable_credentials_spec.rb index 0ba6d64a..c1ca387f 100644 --- a/spec/googleauth/external_account/pluggable_credentials_spec.rb +++ b/spec/googleauth/external_account/pluggable_credentials_spec.rb @@ -228,7 +228,7 @@ } } }, - :file_content => MultiJson.dump(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN), + :file_content => MultiJSON.generate(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN), :expect_token => EXECUTABLE_OIDC_TOKEN }, { @@ -244,7 +244,7 @@ } } }, - :file_content => MultiJson.dump(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_JWT), + :file_content => MultiJSON.generate(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_JWT), :expect_token => EXECUTABLE_OIDC_TOKEN }, { @@ -260,7 +260,7 @@ } } }, - :file_content => MultiJson.dump(EXECUTABLE_SUCCESSFUL_SAML_RESPONSE), + :file_content => MultiJSON.generate(EXECUTABLE_SUCCESSFUL_SAML_RESPONSE), :expect_token => EXECUTABLE_SAML_TOKEN } ] @@ -329,7 +329,7 @@ } }, :executable_return => { - :stdout => MultiJson.dump({}), + :stdout => MultiJSON.generate({}), :stderr => "", :exit_status => 0, }, @@ -348,7 +348,7 @@ } }, :executable_return => { - :stdout => MultiJson.dump({:version => 1}), + :stdout => MultiJSON.generate({:version => 1}), :stderr => "", :exit_status => 0 }, @@ -367,7 +367,7 @@ } }, :executable_return => { - :stdout => MultiJson.dump({:version => 1, :success => false}), + :stdout => MultiJSON.generate({:version => 1, :success => false}), :stderr => "", :exit_status => 0 }, @@ -386,7 +386,7 @@ } }, :executable_return => { - :stdout => MultiJson.dump(EXECUTABLE_FAILED_RESPONSE), + :stdout => MultiJSON.generate(EXECUTABLE_FAILED_RESPONSE), :stderr => "", :exit_status => 0 }, @@ -405,7 +405,7 @@ }, }, :executable_return => { - :stdout => MultiJson.dump({ + :stdout => MultiJSON.generate({ :version => 1, :success => true, :token_type => "urn:ietf:params:oauth:token-type:id_token", @@ -430,7 +430,7 @@ }, }, :executable_return => { - :stdout => MultiJson.dump({ + :stdout => MultiJSON.generate({ :version => 1, :success => true, :id_token => EXECUTABLE_OIDC_TOKEN, @@ -472,7 +472,7 @@ } }, :executable_return => { - :stdout => MultiJson.dump(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN), + :stdout => MultiJSON.generate(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN), :stderr => "", :exit_status => 0 }, @@ -491,7 +491,7 @@ } }, :executable_return => { - :stdout => MultiJson.dump(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_JWT), + :stdout => MultiJSON.generate(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_JWT), :stderr => "", :exit_status => 0 }, @@ -510,7 +510,7 @@ } }, :executable_return => { - :stdout => MultiJson.dump(EXECUTABLE_SUCCESSFUL_SAML_RESPONSE), + :stdout => MultiJSON.generate(EXECUTABLE_SUCCESSFUL_SAML_RESPONSE), :stderr => "", :exit_status => 0 }, diff --git a/spec/googleauth/external_account_spec.rb b/spec/googleauth/external_account_spec.rb index 90a370e6..6f86a2ac 100644 --- a/spec/googleauth/external_account_spec.rb +++ b/spec/googleauth/external_account_spec.rb @@ -31,7 +31,7 @@ end def load_file options - @tempfile.write(MultiJson.dump(options)) + @tempfile.write(MultiJSON.generate(options)) @tempfile.rewind Google::Auth::ExternalAccount::Credentials.make_creds(json_key_io: @tempfile) end @@ -132,7 +132,7 @@ def load_file options it 'should be able to make aws credentials' do f = Tempfile.new('aws') begin - f.write(MultiJson.dump({ + f.write(MultiJSON.generate({ type: 'external_account', audience: '//iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID', subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', @@ -155,7 +155,7 @@ def load_file options it 'should be able to make identity pool credentials' do f = Tempfile.new('file') begin - f.write(MultiJson.dump({ + f.write(MultiJSON.generate({ type: 'external_account', audience: '//iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID', subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', @@ -175,7 +175,7 @@ def load_file options it 'should be able to make pluggable auth credentials' do f = Tempfile.new('file') begin - f.write(MultiJson.dump({ + f.write(MultiJSON.generate({ type: 'external_account', audience: '//iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID', subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', @@ -206,7 +206,7 @@ def load_file options credential_source: {}, } creds.delete(field) - f.write(MultiJson.dump(creds)) + f.write(MultiJSON.generate(creds)) f.rewind expect { Google::Auth::ExternalAccount::Credentials.make_creds(json_key_io: f) }.to raise_error(/the json is missing the #{field} field/) ensure @@ -219,7 +219,7 @@ def load_file options it 'should raise an error for invalid credentials' do f = Tempfile.new('invalid') begin - f.write(MultiJson.dump({ + f.write(MultiJSON.generate({ type: 'external_account', audience: '//iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID', subject_token_type: 'urn:ietf:params:oauth:token-type:id_token', @@ -244,7 +244,7 @@ def load_file options it 'should raise an error if the credential type is not external_account' do f = Tempfile.new('invalid_type') begin - f.write(MultiJson.dump({ + f.write(MultiJSON.generate({ type: 'service_account', audience: '//iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID', subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', @@ -263,7 +263,7 @@ def load_file options it 'should succeed if the credential type is missing (uses default)' do f = Tempfile.new('missing_type') begin - f.write(MultiJson.dump({ + f.write(MultiJSON.generate({ audience: '//iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID', subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', token_url: 'https://sts.googleapis.com/v1/token', diff --git a/spec/googleauth/get_application_default_spec.rb b/spec/googleauth/get_application_default_spec.rb index 213f8df6..12b038f7 100644 --- a/spec/googleauth/get_application_default_spec.rb +++ b/spec/googleauth/get_application_default_spec.rb @@ -204,7 +204,7 @@ end def cred_json_text - MultiJson.dump cred_json + MultiJSON.generate cred_json end it_behaves_like "it can successfully load credentials" @@ -222,7 +222,7 @@ def cred_json_text end def cred_json_text - MultiJson.dump cred_json + MultiJSON.generate cred_json end it_behaves_like "it can successfully load credentials" @@ -248,7 +248,7 @@ def cred_json_text Dir.mktmpdir do |dir| key_path = File.join dir, "my_cert_file" FileUtils.mkdir_p File.dirname(key_path) - File.write key_path, MultiJson.dump(cred_json) + File.write key_path, MultiJSON.generate(cred_json) ENV[@var_name] = key_path creds = Google::Auth.get_application_default @scope, options expect(creds).to be_a(Google::Auth::ImpersonatedServiceAccountCredentials) @@ -285,7 +285,7 @@ def cred_json_text end def cred_json_text - MultiJson.dump cred_json + MultiJSON.generate cred_json end it "fails if the GOOGLE_APPLICATION_CREDENTIALS file contains the creds" do diff --git a/spec/googleauth/impersonated_service_account_spec.rb b/spec/googleauth/impersonated_service_account_spec.rb index 9a8a8144..ade911d8 100644 --- a/spec/googleauth/impersonated_service_account_spec.rb +++ b/spec/googleauth/impersonated_service_account_spec.rb @@ -16,7 +16,7 @@ require_relative "../spec_helper" describe Google::Auth::ImpersonatedServiceAccountCredentials do - + describe ".make_creds with json_key_io" do let(:key) { OpenSSL::PKey::RSA.new 2048 } @@ -52,7 +52,7 @@ it "creates credentials with UserRefreshCredentials as source" do creds = Google::Auth::ImpersonatedServiceAccountCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(impersonated_json)) + json_key_io: StringIO.new(MultiJSON.generate(impersonated_json)) ) expect(creds).to be_a(Google::Auth::ImpersonatedServiceAccountCredentials) @@ -67,7 +67,7 @@ it "creates credentials with ServiceAccountCredentials as source" do creds = Google::Auth::ImpersonatedServiceAccountCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(impersonated_json)) + json_key_io: StringIO.new(MultiJSON.generate(impersonated_json)) ) expect(creds).to be_a(Google::Auth::ImpersonatedServiceAccountCredentials) @@ -92,7 +92,7 @@ it "raises a runtime error" do expect { Google::Auth::ImpersonatedServiceAccountCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(recursive_impersonated_json)) + json_key_io: StringIO.new(MultiJSON.generate(recursive_impersonated_json)) ) }.to raise_error(Google::Auth::InitializationError, /Source credentials can't be of type.*use delegates/) end @@ -103,28 +103,28 @@ it "uses scope from JSON if not provided in options" do creds = Google::Auth::ImpersonatedServiceAccountCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(impersonated_json)) + json_key_io: StringIO.new(MultiJSON.generate(impersonated_json)) ) expect(creds.scope).to eq(["scope1"]) end it "uses scope from options if provided" do creds = Google::Auth::ImpersonatedServiceAccountCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(impersonated_json)), + json_key_io: StringIO.new(MultiJSON.generate(impersonated_json)), scope: ["scope2"] ) expect(creds.scope).to eq(["scope2"]) end end end - + let(:impersonation_url) {"https://iamcredentials.example.com/v1/projects/-/serviceAccounts/test:generateAccessToken"} def make_auth_stubs opts body_fields = { "token_type" => "Bearer", "expires_in" => 3600 } body_fields["accessToken"] = opts[:access_token] body_fields["expireTime"] = opts[:expireTime] - body = MultiJson.dump body_fields + body = MultiJSON.generate body_fields stub_request(:post, impersonation_url) .to_return(body: body, status: opts[:status] || 200, @@ -233,7 +233,7 @@ def make_error_stub(status, body = "error message") hash = {} creds.apply!(hash) - + expect(@stub).to have_been_requested expect(hash[Google::Auth::ImpersonatedServiceAccountCredentials::AUTH_METADATA_KEY]).to eq("Bearer 1/abcde") end @@ -246,7 +246,7 @@ def make_error_stub(status, body = "error message") }) creds.apply!({}) - + expect(creds.access_token).to eq("1/abcde") expect(creds.expires_within? 3600).to be true end @@ -260,22 +260,22 @@ def make_error_stub(status, body = "error message") ) @dup_creds = @initial_creds.duplicate end - + it "should duplicate the scope" do expect(@dup_creds.scope).to eq ["https://www.googleapis.com/auth/cloud-platform"] expect(@dup_creds.duplicate(scope: ["https://www.googleapis.com/auth/devstorage.read_only"]).scope).to eq ["https://www.googleapis.com/auth/devstorage.read_only"] end - + it "should duplicate the base_credentials" do expect(@dup_creds.base_credentials).to eq @base_creds expect(@dup_creds.duplicate(base_credentials: :bar).base_credentials).to eq :bar end - + it "should duplicate the source credentials" do expect(@dup_creds.source_credentials).to eq @source_creds expect(@dup_creds.duplicate(source_credentials: :bar).source_credentials).to eq :bar end - + it "should duplicate the impersonation_url" do expect(@dup_creds.impersonation_url).to eq "test-impersonation-url" expect(@dup_creds.duplicate(impersonation_url: "test-impersonation-url-2").impersonation_url).to eq "test-impersonation-url-2" @@ -291,10 +291,10 @@ def make_error_stub(status, body = "error message") impersonation_url: impersonation_url, scope: ["https://www.googleapis.com/auth/cloud-platform"] ) - + # Allow the principal method to be called on our mock source_creds allow(@source_creds).to receive(:principal).and_return("test-principal") - + expect { creds.send(:normalize_timestamp, 12345) }.to raise_error do |error| expect(error).to be_a(Google::Auth::CredentialsError) expect(error.message).to match(/Invalid time value 12345/) @@ -319,14 +319,14 @@ def make_error_stub(status, body = "error message") context "when response status is 403" do it "raises UnexpectedStatusError with detailed information" do stub = make_error_stub(403, "Permission denied") - + expect { creds.apply!({}) }.to raise_error do |error| expect(error).to be_a(Google::Auth::UnexpectedStatusError) expect(error.message).to match(/Unexpected error code 403.\n Permission denied/) expect(error.credential_type_name).to eq("Google::Auth::ImpersonatedServiceAccountCredentials") expect(error.principal).to eq("test-principal") end - + expect(stub).to have_been_requested end end @@ -334,14 +334,14 @@ def make_error_stub(status, body = "error message") context "when response status is 500" do it "raises UnexpectedStatusError with detailed information" do stub = make_error_stub(500, "Internal server error") - + expect { creds.apply!({}) }.to raise_error do |error| expect(error).to be_a(Google::Auth::UnexpectedStatusError) expect(error.message).to match(/Unexpected error code 500.\n Internal server error/) expect(error.credential_type_name).to eq("Google::Auth::ImpersonatedServiceAccountCredentials") expect(error.principal).to eq("test-principal") end - + expect(stub).to have_been_requested end end @@ -349,14 +349,14 @@ def make_error_stub(status, body = "error message") context "when response status is other error code (e.g. 401)" do it "raises AuthorizationError with detailed information" do stub = make_error_stub(401, "Unauthorized") - + expect { creds.apply!({}) }.to raise_error do |error| expect(error).to be_a(Google::Auth::AuthorizationError) expect(error.message).to match(/Unexpected error code 401.\n Unauthorized/) expect(error.credential_type_name).to eq("Google::Auth::ImpersonatedServiceAccountCredentials") expect(error.principal).to eq("test-principal") end - + expect(stub).to have_been_requested end end diff --git a/spec/googleauth/service_account_jwt_header_spec.rb b/spec/googleauth/service_account_jwt_header_spec.rb index 8d52ecdd..42d5da76 100644 --- a/spec/googleauth/service_account_jwt_header_spec.rb +++ b/spec/googleauth/service_account_jwt_header_spec.rb @@ -55,7 +55,7 @@ end def cred_json_text - MultiJson.dump cred_json + MultiJSON.generate cred_json end it_behaves_like "jwt header auth" diff --git a/spec/googleauth/service_account_spec.rb b/spec/googleauth/service_account_spec.rb index 25b4cd49..5e5191ef 100644 --- a/spec/googleauth/service_account_spec.rb +++ b/spec/googleauth/service_account_spec.rb @@ -79,7 +79,7 @@ def make_auth_stubs opts else raise "Expected access_token or id_token" end - body = MultiJson.dump body_fields + body = MultiJSON.generate body_fields blk = proc do |request| params = Addressable::URI.form_unencode request.body claim, _header = JWT.decode(params.assoc("assertion").last, @@ -97,11 +97,11 @@ def make_auth_stubs opts end def cred_json_text - MultiJson.dump cred_json + MultiJSON.generate cred_json end def cred_json_text_with_universe_domain - MultiJson.dump cred_json_with_universe_domain + MultiJSON.generate cred_json_with_universe_domain end it_behaves_like "apply/apply! are OK" @@ -110,7 +110,7 @@ def cred_json_text_with_universe_domain cred_json[:type] = "authorized_user" expect do ServiceAccountCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(cred_json)) + json_key_io: StringIO.new(MultiJSON.generate(cred_json)) ) end.to raise_error( Google::Auth::InitializationError, @@ -123,7 +123,7 @@ def cred_json_text_with_universe_domain key_without_type = cred_json.reject { |k, _| k == :type } expect do ServiceAccountCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(key_without_type)) + json_key_io: StringIO.new(MultiJSON.generate(key_without_type)) ) end.not_to raise_error( Google::Auth::InitializationError, /The provided credentials were not of type 'service_account'/ @@ -389,12 +389,12 @@ def cred_json_text_with_universe_domain end end end - + describe "duplicates" do before :example do @clz = ServiceAccountCredentials @base_creds = @clz.make_creds( - json_key_io: StringIO.new(cred_json_text), + json_key_io: StringIO.new(cred_json_text), scope: ["https://www.googleapis.com/auth/cloud-platform"] ) @creds = @base_creds.duplicate diff --git a/spec/googleauth/signet_spec.rb b/spec/googleauth/signet_spec.rb index 1fee5ebc..c4817c07 100644 --- a/spec/googleauth/signet_spec.rb +++ b/spec/googleauth/signet_spec.rb @@ -45,7 +45,7 @@ def make_auth_stubs opts body_fields = { "token_type" => "Bearer", "expires_in" => 3600 } body_fields["access_token"] = opts[:access_token] if opts[:access_token] body_fields["id_token"] = opts[:id_token] if opts[:id_token] - body = MultiJson.dump body_fields + body = MultiJSON.generate body_fields blk = proc do |request| params = Addressable::URI.form_unencode request.body claim, _header = JWT.decode(params.assoc("assertion").last, @@ -217,7 +217,7 @@ def make_auth_stubs opts it "should duplicate the authorization_uri" do expect(@creds.authorization_uri).to eq nil expect(@creds.duplicate({ - client_id: "test-client-id-2", + client_id: "test-client-id-2", authorization_uri: "https://test-authorization-uri.example.com", redirect_uri: "https://test-redirect-uri.example.com" }).authorization_uri.to_s.start_with?("https://test-authorization-uri.example.com")).to be true diff --git a/spec/googleauth/user_authorizer_spec.rb b/spec/googleauth/user_authorizer_spec.rb index 7da156af..2e71def4 100644 --- a/spec/googleauth/user_authorizer_spec.rb +++ b/spec/googleauth/user_authorizer_spec.rb @@ -175,7 +175,7 @@ expect(URI(uri).query).to match(/value2/) end end - + context "when dealing with redirect URIs" do let(:relative_callback_uri) { "/oauth2callback" } let(:relative_authorizer) do @@ -186,7 +186,7 @@ relative_callback_uri ) end - + it "raises CredentialsError with detailed information when base_url is missing with relative URI" do expect { relative_authorizer.get_authorization_url }.to raise_error do |error| expect(error).to be_a(Google::Auth::CredentialsError) @@ -195,7 +195,7 @@ expect(error.principal).to eq("testclient") end end - + it "succeeds when base_url is provided with relative URI" do uri = relative_authorizer.get_authorization_url(base_url: "https://example.com") expect(URI(uri).query).to match(%r{redirect_uri=https://example.com/oauth2callback}) @@ -204,7 +204,7 @@ context "when retrieving tokens" do let :token_json do - MultiJson.dump( + MultiJSON.generate( access_token: "accesstoken", refresh_token: "refreshtoken", expiration_time_millis: 1_441_234_742_000 @@ -253,21 +253,21 @@ expect(authorizer.get_credentials("notauser")).to be_nil end end - + context "with mismatched client_id" do let :mismatched_token_json do - MultiJson.dump( + MultiJSON.generate( client_id: "mismatched_client_id", access_token: "accesstoken", refresh_token: "refreshtoken", expiration_time_millis: 1_441_234_742_000 ) end - + before do token_store.store "user1", mismatched_token_json end - + it "raises CredentialsError with detailed information" do expect { authorizer.get_credentials "user1" }.to raise_error do |error| expect(error).to be_a(Google::Auth::CredentialsError) @@ -302,24 +302,24 @@ end it "should persist the refresh token" do - expect(MultiJson.load(token_json)["refresh_token"]).to eq "refreshtoken" + expect(MultiJSON.parse(token_json)["refresh_token"]).to eq "refreshtoken" end it "should persist the access token" do - expect(MultiJson.load(token_json)["access_token"]).to eq "accesstoken" + expect(MultiJSON.parse(token_json)["access_token"]).to eq "accesstoken" end it "should persist the client id" do - expect(MultiJson.load(token_json)["client_id"]).to eq "testclient" + expect(MultiJSON.parse(token_json)["client_id"]).to eq "testclient" end it "should persist the scope" do - expect(MultiJson.load(token_json)["scope"]).to include("email", "profile") + expect(MultiJSON.parse(token_json)["scope"]).to include("email", "profile") end it "should persist the expiry as milliseconds" do expected_expiry = expiry * 1000 - expect(MultiJson.load(token_json)["expiration_time_millis"]).to eql( + expect(MultiJSON.parse(token_json)["expiration_time_millis"]).to eql( expected_expiry ) end @@ -327,7 +327,7 @@ context "with valid authorization code" do let :token_json do - MultiJson.dump("access_token" => "1/abc123", + MultiJSON.generate("access_token" => "1/abc123", "token_type" => "Bearer", "expires_in" => 3600) end @@ -382,7 +382,7 @@ context "when reovking authorization" do let :token_json do - MultiJson.dump( + MultiJSON.generate( access_token: "accesstoken", refresh_token: "refreshtoken", expiration_time_millis: 1_441_234_742_000 diff --git a/spec/googleauth/user_refresh_spec.rb b/spec/googleauth/user_refresh_spec.rb index 266d19ce..d4f4796d 100644 --- a/spec/googleauth/user_refresh_spec.rb +++ b/spec/googleauth/user_refresh_spec.rb @@ -60,7 +60,7 @@ def make_auth_stubs opts access_token = opts[:access_token] || "" - body = MultiJson.dump("access_token" => access_token, + body = MultiJSON.generate("access_token" => access_token, "token_type" => "Bearer", "expires_in" => 3600) stub_request(:post, "https://oauth2.googleapis.com/token") @@ -72,12 +72,12 @@ def make_auth_stubs opts def cred_json_text missing = nil cred_json.delete missing.to_sym unless missing.nil? - MultiJson.dump cred_json + MultiJSON.generate cred_json end def cred_json_text_with_universe_domain missing = nil cred_json_with_universe_domain.delete missing.to_sym unless missing.nil? - MultiJson.dump cred_json_with_universe_domain + MultiJSON.generate cred_json_with_universe_domain end it_behaves_like "apply/apply! are OK" @@ -86,7 +86,7 @@ def cred_json_text_with_universe_domain missing = nil cred_json[:type] = "service_account" expect do UserRefreshCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(cred_json)) + json_key_io: StringIO.new(MultiJSON.generate(cred_json)) ) end.to raise_error( Google::Auth::InitializationError, @@ -99,7 +99,7 @@ def cred_json_text_with_universe_domain missing = nil key_without_type = cred_json.reject { |k, _| k == :type } expect do UserRefreshCredentials.make_creds( - json_key_io: StringIO.new(MultiJson.dump(key_without_type)) + json_key_io: StringIO.new(MultiJSON.generate(key_without_type)) ) end.not_to raise_error( Google::Auth::InitializationError, /The provided credentials were not of type 'authorized_user'/ @@ -419,7 +419,7 @@ def cred_json_text_with_universe_domain missing = nil strio = StringIO.new logger = Logger.new strio @client.logger = logger - + # Stub sleep to avoid slow tests allow(@client).to receive(:sleep) diff --git a/spec/googleauth/web_user_authorizer_spec.rb b/spec/googleauth/web_user_authorizer_spec.rb index ad075ffe..93f52338 100644 --- a/spec/googleauth/web_user_authorizer_spec.rb +++ b/spec/googleauth/web_user_authorizer_spec.rb @@ -41,14 +41,14 @@ ) end let(:request) { Rack::Request.new env } - + it "should raise InitializationError if request is nil" do expect { authorizer.get_authorization_url }.to raise_error do |error| expect(error).to be_a(Google::Auth::InitializationError) expect(error.message).to eq("Request is required.") end end - + it "should raise InitializationError if session is nil" do req_without_session = double("request", session: nil) expect { authorizer.get_authorization_url(request: req_without_session) }.to raise_error do |error| @@ -56,7 +56,7 @@ expect(error.message).to eq("Sessions must be enabled") end end - + it "should include current url in state" do url = authorizer.get_authorization_url request: request expect(url).to match( @@ -115,7 +115,7 @@ shared_examples "handles callback" do let :token_json do - MultiJson.dump("access_token" => "1/abc123", + MultiJSON.generate("access_token" => "1/abc123", "token_type" => "Bearer", "expires_in" => 3600) end @@ -161,7 +161,7 @@ end end end - + describe "#handle_auth_callback" do let(:result) { authorizer.handle_auth_callback "user1", request } @@ -169,7 +169,7 @@ let(:next_url) { result[1] } it_behaves_like "handles callback" - + context "when code is missing from request" do let :env do Rack::MockRequest.env_for( @@ -179,13 +179,13 @@ "REMOTE_ADDR" => "10.10.10.10" ) end - + let(:request) { Rack::Request.new env } - + before :example do request.session["g-xsrf-token"] = "abc" end - + it "should fail with AuthorizationError with detailed information" do expect { authorizer.handle_auth_callback "user1", request }.to raise_error do |error| expect(error).to be_a(Google::Auth::AuthorizationError) @@ -195,7 +195,7 @@ end end end - + context "when error is present in callback state" do let :env do Rack::MockRequest.env_for( @@ -205,13 +205,13 @@ "REMOTE_ADDR" => "10.10.10.10" ) end - + let(:request) { Rack::Request.new env } - + before :example do request.session["g-xsrf-token"] = "abc" end - + it "should fail with AuthorizationError with detailed information" do expect { authorizer.handle_auth_callback "user1", request }.to raise_error do |error| expect(error).to be_a(Google::Auth::AuthorizationError) @@ -234,7 +234,7 @@ end it_behaves_like "handles callback" - + context "when code is missing from request" do let :env do Rack::MockRequest.env_for( @@ -244,14 +244,14 @@ "REMOTE_ADDR" => "10.10.10.10" ) end - + let(:request) { Rack::Request.new env } - + before :example do request.session["g-xsrf-token"] = "abc" Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred request end - + it "should fail with AuthorizationError with detailed information" do expect { authorizer.get_credentials "user1", request }.to raise_error do |error| expect(error).to be_a(Google::Auth::AuthorizationError) @@ -261,7 +261,7 @@ end end end - + context "when error is present in callback state" do let :env do Rack::MockRequest.env_for( @@ -271,14 +271,14 @@ "REMOTE_ADDR" => "10.10.10.10" ) end - + let(:request) { Rack::Request.new env } - + before :example do request.session["g-xsrf-token"] = "abc" Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred request end - + it "should fail with AuthorizationError with detailed information" do expect { authorizer.get_credentials "user1", request }.to raise_error do |error| expect(error).to be_a(Google::Auth::AuthorizationError) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index b3c500a4..acb79245 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -29,7 +29,7 @@ require "google/cloud/env" # Preload adapter to work around Rubinius error with FakeFS -MultiJson.use :json_gem +MultiJSON.use :json_gem # Allow Faraday to support test stubs Faraday::Adapter.lookup_middleware :test diff --git a/test/client_id_test.rb b/test/client_id_test.rb index d494127a..ef9ab019 100644 --- a/test/client_id_test.rb +++ b/test/client_id_test.rb @@ -24,11 +24,11 @@ def self.included spec # Memoize because this included hook gets called multiple times. valid_config_checks = @valid_config_checks ||= Module.new do extend Minitest::Spec::DSL - + it "should include a valid id" do _(client_id.id).must_equal "abc@example.com" end - + it "should include a valid secret" do _(client_id.secret).must_equal "notasecret" end @@ -47,7 +47,7 @@ def self.included spec file_path = "/client_secrets.json" let :client_id do FakeFS do - content = MultiJson.dump config + content = MultiJSON.generate config File.write file_path, content Google::Auth::ClientId.from_file file_path end diff --git a/test/json_key_reader_test.rb b/test/json_key_reader_test.rb index 2515a3d0..8ceb4bd1 100644 --- a/test/json_key_reader_test.rb +++ b/test/json_key_reader_test.rb @@ -23,7 +23,7 @@ class DummyKeyReader describe Google::Auth::JsonKeyReader do let(:dummy_reader) { DummyKeyReader.new } - + describe "#read_json_key" do it "reads all fields from a valid JSON key" do json_key_hash = { @@ -33,45 +33,45 @@ class DummyKeyReader "quota_project_id" => "quota-project", "universe_domain" => "googleapis.com" } - - json_key_io = StringIO.new(MultiJson.dump(json_key_hash)) - - private_key, client_email, project_id, quota_project_id, universe_domain = + + json_key_io = StringIO.new(MultiJSON.generate(json_key_hash)) + + private_key, client_email, project_id, quota_project_id, universe_domain = dummy_reader.read_json_key(json_key_io) - + _(private_key).must_equal "dummy-key" _(client_email).must_equal "dummy@example.com" _(project_id).must_equal "dummy-project" _(quota_project_id).must_equal "quota-project" _(universe_domain).must_equal "googleapis.com" end - + it "raises InitializationError when client_email is missing" do json_key_hash = { "private_key" => "dummy-key" } - - json_key_io = StringIO.new(MultiJson.dump(json_key_hash)) - + + json_key_io = StringIO.new(MultiJSON.generate(json_key_hash)) + error = assert_raises Google::Auth::InitializationError do dummy_reader.read_json_key(json_key_io) end - + _(error.message).must_equal "missing client_email" end - + it "raises InitializationError when private_key is missing" do json_key_hash = { "client_email" => "dummy@example.com" } - - json_key_io = StringIO.new(MultiJson.dump(json_key_hash)) - + + json_key_io = StringIO.new(MultiJSON.generate(json_key_hash)) + error = assert_raises Google::Auth::InitializationError do dummy_reader.read_json_key(json_key_io) end - + _(error.message).must_equal "missing private_key" end end -end \ No newline at end of file +end diff --git a/test/principal_test.rb b/test/principal_test.rb index 13851554..902dacbc 100644 --- a/test/principal_test.rb +++ b/test/principal_test.rb @@ -67,7 +67,7 @@ client_email: test_email, type: "service_account" } - key_io = StringIO.new MultiJson.dump(json) + key_io = StringIO.new MultiJSON.generate(json) creds = Google::Auth::ServiceAccountCredentials.make_creds json_key_io: key_io _(creds.principal).must_equal test_email end @@ -80,7 +80,7 @@ private_key: @key = OpenSSL::PKey::RSA.new(2048).to_pem, client_email: test_email } - key_io = StringIO.new MultiJson.dump(json) + key_io = StringIO.new MultiJSON.generate(json) creds = Google::Auth::ServiceAccountJwtHeaderCredentials.make_creds json_key_io: key_io _(creds.principal).must_equal test_email end @@ -133,7 +133,7 @@ def source_creds.updater_proc refresh_token: "refreshing-token", type: "authorized_user" } - key_io = StringIO.new MultiJson.dump(json) + key_io = StringIO.new MultiJSON.generate(json) creds = Google::Auth::UserRefreshCredentials.make_creds json_key_io: key_io _(creds.principal).must_equal test_client_id end