# Copyright 2015 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "jwt" require "json" require "stringio" require "google/logging/message" require "googleauth/signet" require "googleauth/credentials_loader" require "googleauth/json_key_reader" require "googleauth/service_account_jwt_header" module Google # Module Auth provides classes that provide Google-specific authorization # used to access Google APIs. module Auth # Authenticates requests using Google's Service Account credentials via an # OAuth access token. # # This class allows authorizing requests for service accounts directly # from credentials from a json key file downloaded from the developer # console (via 'Generate new Json Key'). # # cf [Application Default Credentials](https://cloud.google.com/docs/authentication/production) class ServiceAccountCredentials < Signet::OAuth2::Client TOKEN_CRED_URI = "https://www.googleapis.com/oauth2/v4/token".freeze extend CredentialsLoader extend JsonKeyReader attr_reader :project_id attr_reader :quota_project_id # @private # @type [::String] The type name for this credential. CREDENTIAL_TYPE_NAME = "service_account".freeze DEFAULT_UNIVERSE_DOMAIN = "googleapis.com".freeze private_constant :DEFAULT_UNIVERSE_DOMAIN # @private # @type [Array] Allowed option keys for make_creds. VALID_MAKE_CREDS_OPTIONS = [ :json_key_io, :scope, :enable_self_signed_jwt, :target_audience, :audience, :token_credential_uri, :default_connection, :connection_builder ].freeze def enable_self_signed_jwt? # Use a self-singed JWT if there's no information that can be used to # obtain an OAuth token, OR if there are scopes but also an assertion # that they are default scopes that shouldn't be used to fetch a token, # OR we are not in the default universe and thus OAuth isn't supported. target_audience.nil? && (scope.nil? || token_credential_uri.nil? || @enable_self_signed_jwt || non_default_universe_domain?) end # Creates a ServiceAccountCredentials. # # @param json_key_io [IO, nil] Optional. An IO object containing the JSON key # @param scope [String, Array, nil] Optional. The scope(s) to access # @param enable_self_signed_jwt [Boolean, nil] Optional. Whether to use self-signed JWTs # @param target_audience [String, nil] Optional. The target audience for ID token requests # @param audience [String, nil] Optional. Custom token endpoint audience URI # @param token_credential_uri [String, nil] Optional. Custom token credential URI # @param default_connection [Faraday::Connection, nil] Optional. The connection object to use # @param connection_builder [Proc, nil] Optional. A Proc that returns a Faraday connection # @raise [ArgumentError] If both scope and target_audience are specified # @raise [InitializationError] If json_key_io is not an IO object, # if required credential fields (private_key or client_email) are missing, # or if target_audience is specified for a non-default universe domain def self.make_creds options = {} validate_make_creds_options options json_key_io, scope, enable_self_signed_jwt, target_audience, audience, token_credential_uri = options.values_at :json_key_io, :scope, :enable_self_signed_jwt, :target_audience, :audience, :token_credential_uri raise ArgumentError, "Cannot specify both scope and target_audience" if scope && target_audience private_key, client_email, project_id, quota_project_id, universe_domain = load_credentials json_key_io raise InitializationError, "Missing required field: private_key" unless private_key raise InitializationError, "Missing required field: client_email" unless client_email project_id ||= CredentialsLoader.load_gcloud_project_id universe_domain = DEFAULT_UNIVERSE_DOMAIN if universe_domain.nil? default_token_uri = universe_domain == DEFAULT_UNIVERSE_DOMAIN ? TOKEN_CRED_URI : nil new(token_credential_uri: token_credential_uri || default_token_uri, audience: audience || default_token_uri, scope: scope, enable_self_signed_jwt: enable_self_signed_jwt, target_audience: target_audience, issuer: client_email, signing_key: OpenSSL::PKey::RSA.new(private_key), project_id: project_id, quota_project_id: quota_project_id, universe_domain: universe_domain) .configure_connection(options) end # Creates a duplicate of these credentials # without the Signet::OAuth2::Client-specific # transient state (e.g. cached tokens) # # @param options [Hash] Overrides for the credentials parameters. # The following keys are recognized in addition to keys in the # Signet::OAuth2::Client # * `:enable_self_signed_jwt` Whether the self-signed JWT should # be used for the authentication # * `project_id` the project id to use during the authentication # * `quota_project_id` the quota project id to use # during the authentication def duplicate options = {} options = deep_hash_normalize options super( { enable_self_signed_jwt: @enable_self_signed_jwt, project_id: project_id, quota_project_id: quota_project_id, logger: logger }.merge(options) ) end # Handles certain escape sequences that sometimes appear in input. # Specifically, interprets the "\n" sequence for newline, and removes # enclosing quotes. # # @param str [String] The string to unescape # @return [String, nil] The unescaped string, or nil if input is nil def self.unescape str return nil unless str str = str.gsub '\n', "\n" str = str[1..-2] if str.start_with?('"') && str.end_with?('"') str end def initialize options = {} options ||= {} @project_id = nil @quota_project_id = nil @enable_self_signed_jwt = false @universe_domain = DEFAULT_UNIVERSE_DOMAIN super options end # Sets the universe domain for these credentials, normalizing `nil` to # the default universe domain (`googleapis.com`). # # @param value [String, nil] The universe domain. # @raise [Google::Auth::InitializationError] If a non-default universe # domain is combined with a non-nil `target_audience`. def universe_domain= value value = normalized_universe_domain value validate_target_audience_universe_domain! target_audience, value super value end # Sets the target audience for ID token requests. # # @param new_target_audience [String, nil] The target audience. # @raise [Google::Auth::InitializationError] If a non-nil `target_audience` # is set for a non-default universe domain. def target_audience= new_target_audience validate_target_audience_universe_domain! new_target_audience, universe_domain super end # Fetches an OAuth 2.0 token from the token endpoint. # # @param options [Hash] Options forwarded to `Signet::OAuth2::Client#fetch_access_token`. # @raise [Google::Auth::CredentialsError] If called with a non-default universe domain. def fetch_access_token options = {} ensure_default_universe_domain! "fetch_access_token" super end # Fetches an OAuth 2.0 token from the token endpoint and updates client state. # # @param options [Hash] Options forwarded to `Signet::OAuth2::Client#fetch_access_token!`. # @raise [Google::Auth::CredentialsError] If called with a non-default universe domain. def fetch_access_token! options = {} ensure_default_universe_domain! "fetch_access_token!" super end # Generates an OAuth 2.0 access token request payload. # # @param options [Hash] Options forwarded to `Signet::OAuth2::Client#generate_access_token_request`. # @raise [Google::Auth::CredentialsError] If called with a non-default universe domain. def generate_access_token_request options = {} ensure_default_universe_domain! "generate_access_token_request" super end # Signs a JWT assertion for OAuth 2.0 token exchange. # # @param options [Hash] Options forwarded to `Signet::OAuth2::Client#to_jwt`. # @raise [Google::Auth::CredentialsError] If called with a non-default universe domain. def to_jwt options = {} ensure_default_universe_domain! "to_jwt" super end # Extends the base class to use a transient # ServiceAccountJwtHeaderCredentials for certain cases. def apply! a_hash, opts = {} if enable_self_signed_jwt? apply_self_signed_jwt! a_hash else super end end # Modifies this logic so it also requires self-signed-jwt to be disabled def needs_access_token? super && !enable_self_signed_jwt? end # Destructively updates these credentials # # This method is called by `Signet::OAuth2::Client`'s constructor # # @param options [Hash] Overrides for the credentials parameters. # The following keys are recognized in addition to keys in the # Signet::OAuth2::Client # * `:enable_self_signed_jwt` Whether the self-signed JWT should # be used for the authentication # * `project_id` the project id to use during the authentication # * `quota_project_id` the quota project id to use # during the authentication # @raise [Google::Auth::InitializationError] If the resulting state combines # a non-nil `target_audience` with a non-default universe domain. # @return [Google::Auth::ServiceAccountCredentials] def update! options = {} # Normalize all keys to symbols to allow indifferent access. options = deep_hash_normalize options new_universe_domain = options.key?(:universe_domain) ? normalized_universe_domain(options[:universe_domain]) : universe_domain new_target_audience = options.key?(:target_audience) ? options[:target_audience] : target_audience validate_target_audience_universe_domain! new_target_audience, new_universe_domain # Clear target_audience before super sets a non-default universe_domain so # valid transitions never pass through (non-default universe, non-nil target_audience). self.target_audience = nil if new_target_audience.nil? && new_universe_domain != DEFAULT_UNIVERSE_DOMAIN if options.key? :enable_self_signed_jwt @enable_self_signed_jwt = options[:enable_self_signed_jwt] ? true : false end @project_id = options[:project_id] if options.key? :project_id @quota_project_id = options[:quota_project_id] if options.key? :quota_project_id super options self end # Updates token parameters on these credentials. # # @param options [Hash] Token parameter overrides. # @raise [Google::Auth::InitializationError] If updating `universe_domain` # to a non-default value while `target_audience` is set. # @return [Google::Auth::ServiceAccountCredentials] def update_token! options = {} options = deep_hash_normalize options if options.key? :universe_domain new_ud = normalized_universe_domain options[:universe_domain] validate_target_audience_universe_domain! target_audience, new_ud end super options end # Returns the client email as the principal for service account credentials # @private # @return [String] the email address of the service account def principal @issuer end private def non_default_universe_domain? universe_domain != DEFAULT_UNIVERSE_DOMAIN end def normalized_universe_domain value value.nil? ? DEFAULT_UNIVERSE_DOMAIN : value end def validate_target_audience_universe_domain! audience, domain return if audience.nil? || domain == DEFAULT_UNIVERSE_DOMAIN raise InitializationError, "target_audience is not supported for ServiceAccountCredentials in " \ "non-default universe domain #{domain.inspect} (default is #{DEFAULT_UNIVERSE_DOMAIN})" end def ensure_default_universe_domain! operation return unless non_default_universe_domain? message = "OAuth 2.0 token exchange (#{operation}) is not supported for " \ "ServiceAccountCredentials in non-default universe domain " \ "#{universe_domain.inspect} (default is #{DEFAULT_UNIVERSE_DOMAIN}); " \ "use apply! for self-signed JWT authentication" raise CredentialsError.with_details( message, credential_type_name: self.class.name, principal: principal ) end def apply_self_signed_jwt! a_hash # Use the ServiceAccountJwtHeaderCredentials using the same cred values alt = ServiceAccountJwtHeaderCredentials.new( private_key: @signing_key.to_s, issuer: @issuer, project_id: @project_id, quota_project_id: @quota_project_id, universe_domain: universe_domain, scope: scope, logger: logger ) alt.apply! a_hash end # @private # Loads service account credentials from a JSON key IO or environment variables. def self.load_credentials json_key_io return creds_from_env unless json_key_io raise InitializationError, "Expected an IO object for json_key_io" unless json_key_io.respond_to? :read json_key = JSON.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 JSON.generate(json_key) end CredentialsLoader.load_and_verify_json_key_type json_key_io, CREDENTIAL_TYPE_NAME read_json_key json_key_io end # @private # Loads service account credential details from environment variables. # # @return [Array] An array containing private_key, # client_email, project_id, quota_project_id, and universe_domain. def self.creds_from_env private_key = unescape ENV[CredentialsLoader::PRIVATE_KEY_VAR] client_email = ENV[CredentialsLoader::CLIENT_EMAIL_VAR] project_id = ENV[CredentialsLoader::PROJECT_ID_VAR] [private_key, client_email, project_id, nil, nil] end # @private # Validates options passed to make_creds and emits a warning for unrecognized keys. # # @param options [Hash] The options hash to validate. def self.validate_make_creds_options options return unless options.is_a? Hash unknown_keys = options.keys - VALID_MAKE_CREDS_OPTIONS return if unknown_keys.empty? warn "Unrecognized option(s) for ServiceAccountCredentials.make_creds: #{unknown_keys.map(&:inspect).join ', '}" end private_class_method :load_credentials, :creds_from_env, :validate_make_creds_options end end end