class Google::Auth::Credentials
rubocop:disable Metrics/ClassLength
creds2.scope # => [“example.com/sub_scope”]
creds2 = SubCredentials.default
end
self.scope = “example.com/sub_scope”
# Override the default scope for this subclass
class SubCredentials < MyCredentials
creds.scope # => [“example.com/my_scope”]
creds = MyCredentials.default
# creds is a credentials object suitable for Google API clients
end
self.scope = “example.com/my_scope”
# Set the default scope for these credentials
class MyCredentials < Google::Auth::Credentials
## Example
your subclass, call the ‘audience=` method.
deprecated. For example, instead of setting the `AUDIENCE` constant on
Some older users of this class set options via constants. This usage is
options is not set for a subclass, its superclass is queried.
Note that these options inherit up the class hierarchy. If a particular
endpoint, configured with appropriate values.
Normally, an API client will provide subclasses specific to each
expressed as class attributes, and may differ from endpoint to endpoint.
values for parameters such as scope and audience. These defaults are
Credentials classes are configured with options that dictate default
## Options
sources](cloud.google.com/docs/authentication/external/externally-sourced-credentials).
information, refer to [Validate credential configurations from external
can compromise the security of your systems and data. For more
library. Providing an unvalidated credential configuration to Google APIs
Cloud, you must validate it before providing it to any Google API or
JSON/File/Stream) from an external source for authentication to Google
Important: If you accept a credential configuration (credential
can be instantiated by clients.
In most cases, it is subclassed by API-specific credential classes that
libraries to represent the authentication when connecting to an API.
Credentials is a high-level base class used by Google’s API client
#
def self.audience
-
(String)-
def self.audience lookup_auth_param :audience do lookup_local_constant :AUDIENCE end end
def self.audience= new_audience
-
new_audience(String) --
def self.audience= new_audience @audience = new_audience end
def self.default options = {}
-
(Credentials)-
Parameters:
-
options(Hash) --
def self.default options = {} # First try to find keyfile file or json from environment variables. client = from_env_vars options # Second try to find keyfile file from known file paths. client ||= from_default_paths options # Finally get instantiated client from Google::Auth client ||= from_application_default options client end
def self.env_vars
-
(Array-)
def self.env_vars env_vars_internal || [] end
def self.env_vars= new_env_vars
-
new_env_vars(String, Array) --, nil
def self.env_vars= new_env_vars new_env_vars = Array new_env_vars unless new_env_vars.nil? @env_vars = new_env_vars end
def self.env_vars_internal
- Private: -
def self.env_vars_internal lookup_auth_param :env_vars, :env_vars_internal do # Pull values when PATH_ENV_VARS or JSON_ENV_VARS constants exists. path_env_vars = lookup_local_constant :PATH_ENV_VARS json_env_vars = lookup_local_constant :JSON_ENV_VARS (Array(path_env_vars) + Array(json_env_vars)).flatten.uniq if path_env_vars || json_env_vars end end
def self.from_application_default options
- Private: - Lookup Credentials using Google::Auth.get_application_default.
def self.from_application_default options scope = options[:scope] || self.scope auth_opts = { token_credential_uri: options[:token_credential_uri] || token_credential_uri, audience: options[:audience] || audience, target_audience: options[:target_audience] || target_audience, enable_self_signed_jwt: options[:enable_self_signed_jwt] && options[:scope].nil? } client = Google::Auth.get_application_default scope, auth_opts new client, options end
def self.from_default_paths options
- Private: - Lookup Credentials from default file paths.
def self.from_default_paths options paths.each do |path| next unless path && ::File.file?(path) io = ::StringIO.new ::File.read path return from_io io, options end nil end
def self.from_env_vars options
- Private: - Lookup Credentials from environment variables.
def self.from_env_vars options env_vars.each do |env_var| str = ENV[env_var] next if str.nil? io = if ::File.file? str ::StringIO.new ::File.read str else json = ::JSON.parse str rescue nil json ? ::StringIO.new(str) : nil end next if io.nil? return from_io io, options end nil end
def self.from_io io, options
- Private: - Read credentials from a JSON stream.
def self.from_io io, options creds_input = { json_key_io: io, scope: options[:scope] || scope, target_audience: options[:target_audience] || target_audience, enable_self_signed_jwt: options[:enable_self_signed_jwt] && options[:scope].nil?, token_credential_uri: options[:token_credential_uri] || token_credential_uri, audience: options[:audience] || audience } # Determine the class, which consumes the IO stream 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) client = clz.make_creds creds_input options = options.select { |k, _v| k == :logger } new client, options end
def self.init_client hash, options = {}
- Private: -
def self.init_client hash, options = {} options = update_client_options options io = StringIO.new JSON.generate hash # Determine the class, which consumes the IO stream 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) clz.make_creds options.merge!(json_key_io: new_io) end
def self.lookup_auth_param name, method_name = name
-
(Object)- The value
Parameters:
-
method_name(Symbol) -- The lookup method name, if different -
name(Symbol) -- The parameter name
Other tags:
- Private: -
def self.lookup_auth_param name, method_name = name val = instance_variable_get :"@#{name}" val = yield if val.nil? && block_given? return val unless val.nil? return superclass.send method_name if superclass.respond_to? method_name nil end
def self.lookup_local_constant name
-
(Object)- The value
Parameters:
-
Name(Symbol) -- of the constant
Other tags:
- Private: -
def self.lookup_local_constant name const_defined?(name, false) ? const_get(name) : nil end
def self.paths
-
(Array-)
def self.paths paths_internal || [] end
def self.paths= new_paths
-
new_paths(String, Array) --, nil
def self.paths= new_paths new_paths = Array new_paths unless new_paths.nil? @paths = new_paths end
def self.paths_internal
- Private: -
def self.paths_internal lookup_auth_param :paths, :paths_internal do # Pull in values if the DEFAULT_PATHS constant exists. vals = lookup_local_constant :DEFAULT_PATHS vals ? Array(vals).flatten.uniq : nil end end
def self.scope
-
(String, Array-, nil)
def self.scope lookup_auth_param :scope do vals = lookup_local_constant :SCOPE vals ? Array(vals).flatten.uniq : nil end end
def self.scope= new_scope
-
new_scope(String, Array) --, nil
def self.scope= new_scope new_scope = Array new_scope unless new_scope.nil? @scope = new_scope end
def self.target_audience
-
(String, nil)-
def self.target_audience lookup_auth_param :target_audience end
def self.target_audience= new_target_audience
-
new_target_audience(String, nil) --
def self.target_audience= new_target_audience @target_audience = new_target_audience end
def self.token_credential_uri
-
(String)-
def self.token_credential_uri lookup_auth_param :token_credential_uri do lookup_local_constant :TOKEN_CREDENTIAL_URI end end
def self.token_credential_uri= new_token_credential_uri
-
new_token_credential_uri(String) --
def self.token_credential_uri= new_token_credential_uri @token_credential_uri = new_token_credential_uri end
def self.update_client_options options
-
(ArgumentError)- If both scope and target_audience are specified
Returns:
-
(Hash)- Updated options hash
Parameters:
-
options(Hash) -- Options to update
Other tags:
- Private: -
def self.update_client_options options options = options.dup # options have higher priority over constructor defaults options[:token_credential_uri] ||= token_credential_uri options[:audience] ||= audience options[:scope] ||= scope options[:target_audience] ||= target_audience if !Array(options[:scope]).empty? && options[:target_audience] raise ArgumentError, "Cannot specify both scope and target_audience" end options.delete :scope unless options[:target_audience].nil? options end
def deep_hash_normalize old_hash
def deep_hash_normalize old_hash sym_hash = {} old_hash&.each { |k, v| sym_hash[k.to_sym] = recursive_hash_normalize_keys v } sym_hash end
def disable_universe_domain_check
- Private: - Temporary; remove when universe domain metadata endpoint is stable (see b/349488459).
def disable_universe_domain_check return false unless @client.respond_to? :disable_universe_domain_check @client.disable_universe_domain_check end
def duplicate options = {}
-
(Credentials)-
Parameters:
-
options(Hash) -- Overrides for the credentials parameters.
def duplicate options = {} options = deep_hash_normalize options options = { project_id: @project_id, quota_project_id: @quota_project_id }.merge(options) new_client = if @client.respond_to? :duplicate @client.duplicate options else @client end self.class.new new_client, options end
def initialize source_creds, options = {}
-
(ArgumentError)- If both scope and target_audience are specified -
(Google::Auth::InitializationError)- If source_creds is nil
Parameters:
-
options(Hash) -- -
source_creds(String, Pathname, Hash, Google::Auth::BaseClient) --
def initialize source_creds, options = {} if source_creds.nil? raise InitializationError, "The source credentials passed to Google::Auth::Credentials.new were nil." end options = symbolize_hash_keys options @project_id = options[:project_id] || options[:project] @quota_project_id = options[:quota_project_id] case source_creds when String, Pathname update_from_filepath source_creds, options when Hash update_from_hash source_creds, options else update_from_client source_creds end setup_logging logger: options.fetch(:logger, :default) @project_id ||= CredentialsLoader.load_gcloud_project_id @env_vars = nil @paths = nil @scope = nil end
def recursive_hash_normalize_keys val
def recursive_hash_normalize_keys val if val.is_a? Hash deep_hash_normalize val else val end end
def setup_logging logger: :default
def setup_logging logger: :default return unless @client.respond_to? :logger= logging_env = ENV["GOOGLE_SDK_RUBY_LOGGING_GEMS"].to_s.downcase if ["false", "none"].include? logging_env logger = nil elsif @client.logger logger = @client.logger elsif logger == :default logger = nil if ["true", "all"].include?(logging_env) || logging_env.split(",").include?("googleauth") formatter = Google::Logging::StructuredFormatter.new if Google::Cloud::Env.get.logging_agent_expected? logger = Logger.new $stderr, progname: "googleauth", formatter: formatter end end @client.logger = logger end
def stringify_hash_keys hash
def stringify_hash_keys hash hash.to_h.transform_keys(&:to_s) end
def symbolize_hash_keys hash
def symbolize_hash_keys hash hash.to_h.transform_keys(&:to_sym) end
def update_from_client client
def update_from_client client @project_id ||= client.project_id if client.respond_to? :project_id @quota_project_id ||= client.quota_project_id if client.respond_to? :quota_project_id @client = client end
def update_from_filepath path, options
def update_from_filepath path, options verify_keyfile_exists! path json = JSON.parse ::File.read(path) json["scope"] ||= options[:scope] json["target_audience"] ||= options[:target_audience] @project_id ||= json["project_id"] || json["project"] @quota_project_id ||= json["quota_project_id"] @client = self.class.init_client json, options end
def update_from_hash hash, options
def update_from_hash hash, options hash = stringify_hash_keys hash hash["scope"] ||= options[:scope] hash["target_audience"] ||= options[:target_audience] @project_id ||= hash["project_id"] || hash["project"] @quota_project_id ||= hash["quota_project_id"] @client = self.class.init_client hash, options end
def verify_keyfile_exists! keyfile
-
(Google::Auth::InitializationError)- If the keyfile does not exist
Parameters:
-
keyfile(String) -- Path to the keyfile
def verify_keyfile_exists! keyfile exists = ::File.file? keyfile raise InitializationError, "The keyfile '#{keyfile}' is not a valid file." unless exists end