Module: Miasma::Contrib::AwsApiCore::ApiCommon

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/miasma/contrib/aws.rb', line 331

def self.included(klass)
  klass.class_eval do
    attribute :aws_profile_name, [FalseClass, String], :default => 'default'
    attribute :aws_sts_token, String
    attribute :aws_sts_role_arn, String
    attribute :aws_sts_external_id, String
    attribute :aws_sts_role_session_name, String
    attribute :aws_sts_region, String
    attribute :aws_sts_host, String
    attribute :aws_credentials_file, String, :required => true, :default => File.join(Dir.home, '.aws/credentials')
    attribute :aws_config_file, String, :required => true, :default => File.join(Dir.home, '.aws/config')
    attribute :aws_access_key_id, String, :required => true
    attribute :aws_secret_access_key, String, :required => true
    attribute :aws_iam_instance_profile, [TrueClass, FalseClass], :default => false
    attribute :aws_region, String, :required => true
    attribute :aws_host, String
    attribute :aws_bucket_region, String
    attribute :api_endpoint, String, :required => true, :default => 'amazonaws.com'
    attribute :euca_compat, Symbol, :allowed_values => [:path, :dns], :coerce => lambda{|v| v.is_a?(String) ? v.to_sym : v}
    attribute :euca_dns_map, Smash, :coerce => lambda{|v| v.to_smash}, :default => Smash.new
    attribute :ssl_enabled, [TrueClass, FalseClass], :default => true

    # @return [Contrib::AwsApiCore::SignatureV4]
    attr_reader :signer
  end

  # AWS config file key remapping
  klass.const_set(:CONFIG_FILE_REMAP,
    Smash.new(
      'region' => 'aws_region',
      'role_arn' => 'aws_sts_role_arn'
    )
  )
  klass.const_set(:INSTANCE_PROFILE_HOST, 'http://169.254.169.254')
  klass.const_set(:INSTANCE_PROFILE_PATH, 'latest/meta-data/iam/security-credentials')
  klass.const_set(:INSTANCE_PROFILE_AZ_PATH, 'latest/meta-data/placement/availability-zone')
end

Instance Method Details

#after_setup(creds) ⇒ TrueClass

Persist any underlying stored credential data that is not a defined attribute (things like STS information)

Parameters:

  • creds (Hash)

Returns:

  • (TrueClass)


420
421
422
423
424
425
426
427
428
# File 'lib/miasma/contrib/aws.rb', line 420

def after_setup(creds)
  skip = self.class.attributes.keys.map(&:to_s)
  creds.each do |k,v|
    k = k.to_s
    if(k.start_with?('aws_') && !skip.include?(k))
      data[k] = v
    end
  end
end

#api_for(type) ⇒ Api

Build new API for specified type using current provider / creds

Parameters:

  • type (Symbol)

    api type

Returns:

  • (Api)


373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/miasma/contrib/aws.rb', line 373

def api_for(type)
  memoize(type) do
    creds = attributes.dup
    creds.delete(:aws_host)
    Miasma.api(
      Smash.new(
        :type => type,
        :provider => provider,
        :credentials => creds
      )
    )
  end
end

#connectObject

Setup for API connections



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/miasma/contrib/aws.rb', line 555

def connect
  unless(aws_host)
    if(euca_compat)
      service_name = (
        self.class.const_defined?(:EUCA_API_SERVICE) ?
        self.class::EUCA_API_SERVICE :
        self.class::API_SERVICE
      )
    else
      service_name = self.class::API_SERVICE.downcase
    end
    if(euca_compat == :path)
      self.aws_host = [
        api_endpoint,
        'services',
        service_name
      ].join('/')
    elsif(euca_compat == :dns && euca_dns_map[service_name])
      self.aws_host = [
        euca_dns_map[service_name],
        api_endpoint
      ].join('.')
    else
      self.aws_host = [
        service_name,
        aws_region,
        api_endpoint
      ].join('.')
    end
  end
  @signer = Contrib::AwsApiCore::SignatureV4.new(
    aws_access_key_id, aws_secret_access_key, aws_region, self.class::API_SERVICE
  )
end

#connectionHTTP

Returns connection for requests (forces headers).

Returns:

  • (HTTP)

    connection for requests (forces headers)



596
597
598
599
600
601
# File 'lib/miasma/contrib/aws.rb', line 596

def connection
  super.headers(
    'Host' => aws_host,
    'X-Amz-Date' => Contrib::AwsApiCore.time_iso8601
  )
end

#custom_setup(creds) ⇒ TrueClass

Provide custom setup functionality to support alternative credential loading.

Parameters:

  • creds (Hash)

Returns:

  • (TrueClass)


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/miasma/contrib/aws.rb', line 392

def custom_setup(creds)
  if(creds[:aws_profile_name])
    creds.replace(
      load_aws_file(
        aws_config_file,
        creds[:aws_profile_name]
      ).merge(
        load_aws_file(
          aws_credentials_file,
          creds[:aws_profile_name]
        )
      ).merge(creds)
    )
  end
  if(creds[:aws_sts_role_arn])
    sts_assume_role!(creds)
  end
  if(creds[:aws_iam_instance_profile])
    load_instance_credentials!(creds)
  end
  true
end

#endpointString

Returns endpoint for request.

Returns:

  • (String)

    endpoint for request



604
605
606
# File 'lib/miasma/contrib/aws.rb', line 604

def endpoint
  "http#{'s' if ssl_enabled}://#{aws_host}"
end

#load_aws_file(file_path, profile) ⇒ Smash

Load configuration from the AWS configuration file

Parameters:

  • file_path (String)

    path to configuration file

  • profile (String)

    name of profile to load

Returns:

  • (Smash)


507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/miasma/contrib/aws.rb', line 507

def load_aws_file(file_path, profile)
  if(File.exists?(file_path))
    l_config = Smash.new.tap do |creds|
      key = nil
      File.readlines(file_path).each_with_index do |line, idx|
        line.strip!
        next if line.empty? || line.start_with?('#')
        if(line.start_with?('['))
          unless(line.end_with?(']'))
            raise ArgumentError.new("Failed to parse aws file! (#{file_path} line #{idx + 1})")
          end
          key = line.tr('[]', '').strip.sub(/^profile /, '')
          creds[key] = Smash.new
        else
          unless(key)
            raise ArgumentError.new("Failed to parse aws file! (#{file_path} line #{idx + 1}) - No section defined!")
          end
          line_args = line.split('=', 2).map(&:strip)
          line_args.first.replace(
            self.class.const_get(:CONFIG_FILE_REMAP).fetch(
              line_args.first, line_args.first
            )
          )
          begin
            creds[key].merge!(Smash[*line_args])
          rescue => e
            raise ArgumentError.new("Failed to parse aws file! (#{file_path} line #{idx + 1})")
          end
        end
      end
    end

    l_profile = l_config.fetch(profile, Smash.new)
    l_source_profile = l_config.fetch(l_profile[:source_profile], Smash.new)

    l_creds = l_config.fetch(
      :default, Smash.new
    ).merge(
      l_source_profile
    ).merge(
      l_profile
    )
  else
    Smash.new
  end
end

#load_instance_credentials!(creds) ⇒ TrueClass

Attempt to load credentials from instance metadata

Parameters:

  • creds (Hash)

Returns:

  • (TrueClass)


434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/miasma/contrib/aws.rb', line 434

def load_instance_credentials!(creds)
  role = HTTP.get(
    [
      self.class.const_get(:INSTANCE_PROFILE_HOST),
      self.class.const_get(:INSTANCE_PROFILE_PATH),
      ''
    ].join('/')
  ).body.to_s.strip
  data = HTTP.get(
    [
      self.class.const_get(:INSTANCE_PROFILE_HOST),
      self.class.const_get(:INSTANCE_PROFILE_PATH),
      role
    ].join('/')
  ).body
  unless(data.is_a?(Hash))
    begin
      data = MultiJson.load(data.to_s)
    rescue MultiJson::ParseError
      data = {}
    end
  end
  creds[:aws_access_key_id] = data['AccessKeyId']
  creds[:aws_secret_access_key] = data['SecretAccessKey']
  creds[:aws_sts_token] = data['Token']
  creds[:aws_sts_token_expires] = Time.xmlschema(data['Expiration'])
  unless(creds[:aws_region])
    az = HTTP.get(
      [
        self.class.const_get(:INSTANCE_PROFILE_HOST),
        self.class.const_get(:INSTANCE_PROFILE_AZ_PATH)
      ].join('/')
    ).body.to_s.strip
    az.sub!(/[a-zA-Z]+$/, '')
    creds[:aws_region] = az
  end
  true
end

#make_request(connection, http_method, request_args) ⇒ HTTP::Response

Override to inject signature

Parameters:

  • connection (HTTP)
  • http_method (Symbol)
  • request_args (Array)

Returns:

  • (HTTP::Response)


614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
# File 'lib/miasma/contrib/aws.rb', line 614

def make_request(connection, http_method, request_args)
  dest, options = request_args
  path = URI.parse(dest).path
  options = options ? options.to_smash : Smash.new
  options[:headers] = Smash[connection.default_options.headers.to_a].merge(options.fetch(:headers, Smash.new))
  if(self.class::API_VERSION)
    if(options[:form])
      options.set(:form, 'Version', self.class::API_VERSION)
    else
      options[:params] = options.fetch(
        :params, Smash.new
      ).to_smash.deep_merge(
        Smash.new(
          'Version' => self.class::API_VERSION
        )
      )
    end
  end
  if(aws_sts_token)
    sts_assume_role!(attributes) if sts_update_required?
    options.set(:headers, 'X-Amz-Security-Token', aws_sts_token)
  end
  signature = signer.generate(http_method, path, options)
  update_request(connection, options)
  options = Hash[options.map{|k,v|[k.to_sym,v]}]
  connection.auth(signature).send(http_method, dest, options)
end

#perform_request_retry(exception) ⇒ TrueClass, FalseClass

Determine if a retry is allowed based on exception

Parameters:

  • exception (Exception)

Returns:

  • (TrueClass, FalseClass)


662
663
664
665
666
667
668
669
670
671
672
673
674
# File 'lib/miasma/contrib/aws.rb', line 662

def perform_request_retry(exception)
  if(exception.is_a?(Miasma::Error::ApiError))
    if([400, 500, 503].include?(exception.response.code))
      if(exception.response.code == 400)
        exception.response.body.to_s.downcase.include?('throttl')
      else
        true
      end
    else
      false
    end
  end
end

#retryable_allowed?(*_) ⇒ TrueClass

Always allow retry

Returns:

  • (TrueClass)


679
680
681
# File 'lib/miasma/contrib/aws.rb', line 679

def retryable_allowed?(*_)
  true
end

#sts_assume_role!(creds) ⇒ TrueClass

Assume requested role and replace key id and secret

Parameters:

  • creds (Hash)

Returns:

  • (TrueClass)


477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/miasma/contrib/aws.rb', line 477

def sts_assume_role!(creds)
  unless(creds[:aws_access_key_id_original])
    creds[:aws_access_key_id_original] = creds[:aws_access_key_id]
    creds[:aws_secret_access_key_original] = creds[:aws_secret_access_key]
  end
  if(sts_update_required?(creds))
    sts = Miasma::Contrib::Aws::Api::Sts.new(
      :aws_access_key_id => creds[:aws_access_key_id_original],
      :aws_secret_access_key => creds[:aws_secret_access_key_original],
      :aws_region => creds.fetch(:aws_sts_region, 'us-east-1'),
      :aws_credentials_file => creds.fetch(:aws_credentials_file, aws_credentials_file),
      :aws_config_file => creds.fetch(:aws_config_file, aws_config_file),
      :aws_profile_name => creds[:aws_profile_name],
      :aws_host => creds[:aws_sts_host]
    )
    role_info = sts.assume_role(
      creds[:aws_sts_role_arn],
      :session_name => creds[:aws_sts_role_session_name],
      :external_id => creds[:aws_sts_external_id]
    )
    creds.merge!(role_info)
  end
  true
end

#sts_update_required?(args = {}) ⇒ TrueClass, FalseClass

Returns:

  • (TrueClass, FalseClass)


643
644
645
646
647
# File 'lib/miasma/contrib/aws.rb', line 643

def sts_update_required?(args={})
  expiry = args.fetch(:aws_sts_token_expires, data[:aws_sts_token_expires])
  expiry.nil? || expiry <= Time.now - 1
  true
end

#update_request(con, opts) ⇒ TrueClass

Simple callback to allow request option adjustments prior to signature calculation

Parameters:

  • opts (Smash)

    request options

Returns:

  • (TrueClass)


654
655
656
# File 'lib/miasma/contrib/aws.rb', line 654

def update_request(con, opts)
  true
end

#uri_escape(string) ⇒ String

Returns custom escape for aws compat.

Returns:

  • (String)

    custom escape for aws compat



591
592
593
# File 'lib/miasma/contrib/aws.rb', line 591

def uri_escape(string)
  signer.safe_escape(string)
end