File: shared_config.rb

package info (click to toggle)
ruby-aws-sdk-core 3.104.3-3%2Bdeb11u2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,444 kB
  • sloc: ruby: 11,201; makefile: 4
file content (326 lines) | stat: -rw-r--r-- 12,531 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# frozen_string_literal: true

module Aws
  # @api private
  class SharedConfig
    # @return [String]
    attr_reader :credentials_path

    # @return [String]
    attr_reader :config_path

    # @return [String]
    attr_reader :profile_name

    # Constructs a new SharedConfig provider object. This will load the shared
    # credentials file, and optionally the shared configuration file, as ini
    # files which support profiles.
    #
    # By default, the shared credential file (the default path for which is
    # `~/.aws/credentials`) and the shared config file (the default path for
    # which is `~/.aws/config`) are loaded. However, if you set the
    # `ENV['AWS_SDK_CONFIG_OPT_OUT']` environment variable, only the shared
    # credential file will be loaded. You can specify the shared credential
    # file path with the `ENV['AWS_SHARED_CREDENTIALS_FILE']` environment
    # variable or with the `:credentials_path` option. Similarly, you can
    # specify the shared config file path with the `ENV['AWS_CONFIG_FILE']`
    # environment variable or with the `:config_path` option.
    #
    # The default profile name is 'default'. You can specify the profile name
    # with the `ENV['AWS_PROFILE']` environment variable or with the
    # `:profile_name` option.
    #
    # @param [Hash] options
    # @option options [String] :credentials_path Path to the shared credentials
    #   file. If not specified, will check `ENV['AWS_SHARED_CREDENTIALS_FILE']`
    #   before using the default value of "#{Dir.home}/.aws/credentials".
    # @option options [String] :config_path Path to the shared config file.
    #   If not specified, will check `ENV['AWS_CONFIG_FILE']` before using the
    #   default value of "#{Dir.home}/.aws/config".
    # @option options [String] :profile_name The credential/config profile name
    #   to use. If not specified, will check `ENV['AWS_PROFILE']` before using
    #   the fixed default value of 'default'.
    # @option options [Boolean] :config_enabled If true, loads the shared config
    #   file and enables new config values outside of the old shared credential
    #   spec.
    def initialize(options = {})
      @parsed_config = nil
      @profile_name = determine_profile(options)
      @config_enabled = options[:config_enabled]
      @credentials_path = options[:credentials_path] ||
                          determine_credentials_path
      @parsed_credentials = {}
      load_credentials_file if loadable?(@credentials_path)
      if @config_enabled
        @config_path = options[:config_path] || determine_config_path
        load_config_file if loadable?(@config_path)
      end
    end

    # @api private
    def fresh(options = {})
      @profile_name = nil
      @credentials_path = nil
      @config_path = nil
      @parsed_credentials = {}
      @parsed_config = nil
      @config_enabled = options[:config_enabled] ? true : false
      @profile_name = determine_profile(options)
      @credentials_path = options[:credentials_path] ||
                          determine_credentials_path
      load_credentials_file if loadable?(@credentials_path)
      if @config_enabled
        @config_path = options[:config_path] || determine_config_path
        load_config_file if loadable?(@config_path)
      end
    end

    # @return [Boolean] Returns `true` if a credential file
    #   exists and has appropriate read permissions at {#path}.
    # @note This method does not indicate if the file found at {#path}
    #   will be parsable, only if it can be read.
    def loadable?(path)
      !path.nil? && File.exist?(path) && File.readable?(path)
    end

    # @return [Boolean] returns `true` if use of the shared config file is
    #   enabled.
    def config_enabled?
      @config_enabled ? true : false
    end

    # Sources static credentials from shared credential/config files.
    #
    # @param [Hash] opts
    # @option options [String] :profile the name of the configuration file from
    #   which credentials are being sourced.
    # @return [Aws::Credentials] credentials sourced from configuration values,
    #   or `nil` if no valid credentials were found.
    def credentials(opts = {})
      p = opts[:profile] || @profile_name
      validate_profile_exists(p) if credentials_present?
      if (credentials = credentials_from_shared(p, opts))
        credentials
      elsif (credentials = credentials_from_config(p, opts))
        credentials
      end
    end

    # Attempts to assume a role from shared config or shared credentials file.
    # Will always attempt first to assume a role from the shared credentials
    # file, if present.
    def assume_role_credentials_from_config(opts = {})
      p = opts.delete(:profile) || @profile_name
      chain_config = opts.delete(:chain_config)
      credentials = assume_role_from_profile(@parsed_credentials, p, opts, chain_config)
      if @parsed_config
        credentials ||= assume_role_from_profile(@parsed_config, p, opts, chain_config)
      end
      credentials
    end

    def assume_role_web_identity_credentials_from_config(opts = {})
      p = opts[:profile] || @profile_name
      if @config_enabled && @parsed_config
        entry = @parsed_config.fetch(p, {})
        if entry['web_identity_token_file'] && entry['role_arn']
          cfg = {
            role_arn: entry['role_arn'],
            web_identity_token_file: entry['web_identity_token_file'],
            role_session_name: entry['role_session_name']
          }
          cfg[:region] = opts[:region] if opts[:region]
          AssumeRoleWebIdentityCredentials.new(cfg)
        end
      end
    end

    # Add an accessor method (similar to attr_reader) to return a configuration value
    # Uses the get_config_value below to control where
    # values are loaded from
    def self.config_reader(*attrs)
      attrs.each do |attr|
        define_method(attr) { |opts = {}| get_config_value(attr.to_s, opts) }
      end
    end

    config_reader(
      :region,
      :credential_process,
      :endpoint_discovery_enabled,
      :max_attempts,
      :retry_mode,
      :adaptive_retry_wait_to_fill,
      :correct_clock_skew,
      :csm_client_id,
      :csm_enabled,
      :csm_host,
      :csm_port,
      :sts_regional_endpoints,
      :s3_use_arn_region,
      :s3_us_east_1_regional_endpoint
    )

    private

    # Get a config value from from shared credential/config files.
    # Only loads a value when config_enabled is true
    # Return a value from credentials preferentially over config
    def get_config_value(key, opts)
      p = opts[:profile] || @profile_name

      value = @parsed_credentials.fetch(p, {})[key] if @parsed_credentials
      value ||= @parsed_config.fetch(p, {})[key] if @config_enabled && @parsed_config
      value
    end

    def credentials_present?
      (@parsed_credentials && !@parsed_credentials.empty?) ||
        (@parsed_config && !@parsed_config.empty?)
    end

    def assume_role_from_profile(cfg, profile, opts, chain_config)
      if cfg && prof_cfg = cfg[profile]
        opts[:source_profile] ||= prof_cfg['source_profile']
        credential_source = opts.delete(:credential_source)
        credential_source ||= prof_cfg['credential_source']
        if opts[:source_profile] && credential_source
          raise Errors::CredentialSourceConflictError,
            "Profile #{profile} has a source_profile, and "\
            'a credential_source. For assume role credentials, must '\
            'provide only source_profile or credential_source, not both.'
        elsif opts[:source_profile]
          opts[:credentials] = resolve_source_profile(opts[:source_profile], opts)
          if opts[:credentials]
            opts[:role_session_name] ||= prof_cfg['role_session_name']
            opts[:role_session_name] ||= 'default_session'
            opts[:role_arn] ||= prof_cfg['role_arn']
            opts[:duration_seconds] ||= prof_cfg['duration_seconds']
            opts[:external_id] ||= prof_cfg['external_id']
            opts[:serial_number] ||= prof_cfg['mfa_serial']
            opts[:profile] = opts.delete(:source_profile)
            AssumeRoleCredentials.new(opts)
          else
            raise Errors::NoSourceProfileError,
              "Profile #{profile} has a role_arn, and source_profile, but the"\
              ' source_profile does not have credentials.'
          end
        elsif credential_source
          opts[:credentials] = credentials_from_source(
            credential_source,
            chain_config
          )
          if opts[:credentials]
            opts[:role_session_name] ||= prof_cfg['role_session_name']
            opts[:role_session_name] ||= 'default_session'
            opts[:role_arn] ||= prof_cfg['role_arn']
            opts[:duration_seconds] ||= prof_cfg['duration_seconds']
            opts[:external_id] ||= prof_cfg['external_id']
            opts[:serial_number] ||= prof_cfg['mfa_serial']
            opts.delete(:source_profile) # Cleanup
            AssumeRoleCredentials.new(opts)
          else
            raise Errors::NoSourceCredentials,
              "Profile #{profile} could not get source credentials from"\
              " provider #{credential_source}"
          end
        elsif prof_cfg['role_arn']
          raise Errors::NoSourceProfileError, "Profile #{profile} has a role_arn, but no source_profile."
        end
      end
    end

    def resolve_source_profile(profile, opts = {})
      if (creds = credentials(profile: profile))
        creds # static credentials
      elsif (provider = assume_role_web_identity_credentials_from_config(opts.merge(profile: profile)))
        provider.credentials if provider.credentials.set?
      elsif (provider = assume_role_process_credentials_from_config(profile))
        provider.credentials if provider.credentials.set?
      end
    end

    def credentials_from_source(credential_source, config)
      case credential_source
      when 'Ec2InstanceMetadata'
        InstanceProfileCredentials.new(
          retries: config ? config.instance_profile_credentials_retries : 0,
          http_open_timeout: config ? config.instance_profile_credentials_timeout : 1,
          http_read_timeout: config ? config.instance_profile_credentials_timeout : 1
        )
      when 'EcsContainer'
        ECSCredentials.new
      else
        raise Errors::InvalidCredentialSourceError, "Unsupported credential_source: #{credential_source}"
      end
    end

    def assume_role_process_credentials_from_config(profile)
      validate_profile_exists(profile)
      credential_process = @parsed_config[profile]['credential_process']
      ProcessCredentials.new(credential_process) if credential_process
    end

    def credentials_from_shared(profile, _opts)
      if @parsed_credentials && prof_config = @parsed_credentials[profile]
        credentials_from_profile(prof_config)
      end
    end

    def credentials_from_config(profile, _opts)
      if @parsed_config && prof_config = @parsed_config[profile]
        credentials_from_profile(prof_config)
      end
    end

    def credentials_from_profile(prof_config)
      creds = Credentials.new(
        prof_config['aws_access_key_id'],
        prof_config['aws_secret_access_key'],
        prof_config['aws_session_token']
      )
      creds if creds.set?
    end

    def load_credentials_file
      @parsed_credentials = IniParser.ini_parse(
        File.read(@credentials_path)
      )
    end

    def load_config_file
      @parsed_config = IniParser.ini_parse(File.read(@config_path))
    end

    def determine_credentials_path
      ENV['AWS_SHARED_CREDENTIALS_FILE'] || default_shared_config_path('credentials')
    end

    def determine_config_path
      ENV['AWS_CONFIG_FILE'] || default_shared_config_path('config')
    end

    def default_shared_config_path(file)
      File.join(Dir.home, '.aws', file)
    rescue ArgumentError
      # Dir.home raises ArgumentError when ENV['home'] is not set
      nil
    end

    def validate_profile_exists(profile)
      unless (@parsed_credentials && @parsed_credentials[profile]) ||
             (@parsed_config && @parsed_config[profile])
        msg = "Profile `#{profile}' not found in #{@credentials_path}"\
              "#{" or #{@config_path}" if @config_path}"
        raise Errors::NoSuchProfileError, msg
      end
    end

    def determine_profile(options)
      ret = options[:profile_name]
      ret ||= ENV['AWS_PROFILE']
      ret ||= 'default'
      ret
    end
  end
end