aws_assume_role 1.1.0-universal-darwin

Sign up to get free protection for your applications and to get access to all the features.
Files changed (73) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +9 -0
  3. data/.rubocop.yml +57 -0
  4. data/.ruby-version +1 -0
  5. data/.simplecov +22 -0
  6. data/.travis.yml +24 -0
  7. data/CHANGELOG.md +61 -0
  8. data/Gemfile +18 -0
  9. data/LICENSE.md +201 -0
  10. data/README.md +303 -0
  11. data/Rakefile +63 -0
  12. data/aws_assume_role.gemspec +56 -0
  13. data/bin/aws-assume-role +4 -0
  14. data/i18n/en.yml +109 -0
  15. data/lib/aws_assume_role.rb +4 -0
  16. data/lib/aws_assume_role/cli.rb +20 -0
  17. data/lib/aws_assume_role/cli/actions/abstract_action.rb +61 -0
  18. data/lib/aws_assume_role/cli/actions/configure_profile.rb +24 -0
  19. data/lib/aws_assume_role/cli/actions/configure_role_assumption.rb +22 -0
  20. data/lib/aws_assume_role/cli/actions/console.rb +70 -0
  21. data/lib/aws_assume_role/cli/actions/delete_profile.rb +22 -0
  22. data/lib/aws_assume_role/cli/actions/includes.rb +12 -0
  23. data/lib/aws_assume_role/cli/actions/list_profiles.rb +12 -0
  24. data/lib/aws_assume_role/cli/actions/migrate_profile.rb +20 -0
  25. data/lib/aws_assume_role/cli/actions/reset_environment.rb +50 -0
  26. data/lib/aws_assume_role/cli/actions/run.rb +36 -0
  27. data/lib/aws_assume_role/cli/actions/set_environment.rb +62 -0
  28. data/lib/aws_assume_role/cli/actions/test.rb +35 -0
  29. data/lib/aws_assume_role/cli/commands/configure.rb +32 -0
  30. data/lib/aws_assume_role/cli/commands/console.rb +19 -0
  31. data/lib/aws_assume_role/cli/commands/delete.rb +13 -0
  32. data/lib/aws_assume_role/cli/commands/environment.rb +34 -0
  33. data/lib/aws_assume_role/cli/commands/list.rb +12 -0
  34. data/lib/aws_assume_role/cli/commands/migrate.rb +13 -0
  35. data/lib/aws_assume_role/cli/commands/run.rb +19 -0
  36. data/lib/aws_assume_role/cli/commands/test.rb +20 -0
  37. data/lib/aws_assume_role/cli/includes.rb +3 -0
  38. data/lib/aws_assume_role/configuration.rb +30 -0
  39. data/lib/aws_assume_role/core_ext/aws-sdk/credential_provider_chain.rb +4 -0
  40. data/lib/aws_assume_role/core_ext/aws-sdk/includes.rb +9 -0
  41. data/lib/aws_assume_role/credentials/factories.rb +11 -0
  42. data/lib/aws_assume_role/credentials/factories/abstract_factory.rb +33 -0
  43. data/lib/aws_assume_role/credentials/factories/assume_role.rb +39 -0
  44. data/lib/aws_assume_role/credentials/factories/default_chain_provider.rb +113 -0
  45. data/lib/aws_assume_role/credentials/factories/environment.rb +26 -0
  46. data/lib/aws_assume_role/credentials/factories/includes.rb +15 -0
  47. data/lib/aws_assume_role/credentials/factories/instance_profile.rb +19 -0
  48. data/lib/aws_assume_role/credentials/factories/repository.rb +37 -0
  49. data/lib/aws_assume_role/credentials/factories/shared.rb +19 -0
  50. data/lib/aws_assume_role/credentials/factories/static.rb +18 -0
  51. data/lib/aws_assume_role/credentials/includes.rb +6 -0
  52. data/lib/aws_assume_role/credentials/providers/assume_role_credentials.rb +60 -0
  53. data/lib/aws_assume_role/credentials/providers/includes.rb +9 -0
  54. data/lib/aws_assume_role/credentials/providers/mfa_session_credentials.rb +119 -0
  55. data/lib/aws_assume_role/credentials/providers/shared_keyring_credentials.rb +41 -0
  56. data/lib/aws_assume_role/includes.rb +38 -0
  57. data/lib/aws_assume_role/logging.rb +27 -0
  58. data/lib/aws_assume_role/profile_configuration.rb +73 -0
  59. data/lib/aws_assume_role/runner.rb +40 -0
  60. data/lib/aws_assume_role/store/includes.rb +8 -0
  61. data/lib/aws_assume_role/store/keyring.rb +61 -0
  62. data/lib/aws_assume_role/store/serialization.rb +20 -0
  63. data/lib/aws_assume_role/store/shared_config_with_keyring.rb +250 -0
  64. data/lib/aws_assume_role/types.rb +31 -0
  65. data/lib/aws_assume_role/ui.rb +57 -0
  66. data/lib/aws_assume_role/vendored/aws.rb +4 -0
  67. data/lib/aws_assume_role/vendored/aws/README.md +2 -0
  68. data/lib/aws_assume_role/vendored/aws/assume_role_credentials.rb +67 -0
  69. data/lib/aws_assume_role/vendored/aws/includes.rb +9 -0
  70. data/lib/aws_assume_role/vendored/aws/refreshing_credentials.rb +58 -0
  71. data/lib/aws_assume_role/vendored/aws/shared_config.rb +223 -0
  72. data/lib/aws_assume_role/version.rb +5 -0
  73. metadata +438 -0
data/Rakefile ADDED
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "aws_assume_role/version"
4
+ require "bundler/gem_tasks"
5
+ require "yaml"
6
+
7
+ task default: :test
8
+
9
+ begin
10
+ require "rspec/core/rake_task"
11
+ RSpec::Core::RakeTask.new(:spec)
12
+ rescue LoadError # rubocop:disable Lint/HandleExceptions
13
+ end
14
+
15
+ begin
16
+ require "rubocop/rake_task"
17
+ RuboCop::RakeTask.new(:rubocop)
18
+ rescue LoadError # rubocop:disable Lint/HandleExceptions
19
+ end
20
+
21
+ task test: %i[no_pry rubocop spec]
22
+
23
+ DISTRIBUTIONS = [
24
+ "universal-linux",
25
+ "universal-freebsd",
26
+ "universal-darwin",
27
+ "universal-openbsd",
28
+ ].freeze
29
+
30
+ CREDENTIALS = {
31
+ rubygems_api_key: ENV.fetch("API_KEY", "null"),
32
+ }.freeze
33
+
34
+ task :setup_credentials do
35
+ FileUtils.mkdir_p(File.expand_path("~/.gem"))
36
+ File.write(File.expand_path("~/.gem/credentials"), CREDENTIALS.to_yaml)
37
+ end
38
+
39
+ task publish: [:build] do
40
+ Dir.glob("#{File.dirname(__FILE__)}/pkg/*.gem") do |g|
41
+ sh "gem push #{g}"
42
+ end
43
+ end
44
+
45
+ namespace :build_arch do
46
+ DISTRIBUTIONS.each do |arch|
47
+ desc "build binary gem for #{arch}"
48
+ task arch do
49
+ sh "cd #{File.dirname(__FILE__)} && PLATFORM=#{arch} gem build aws_assume_role.gemspec"
50
+ FileUtils.mkdir_p(File.join(File.dirname(__FILE__), "pkg"))
51
+ sh "cd #{File.dirname(__FILE__)} && mv *.gem pkg/"
52
+ end
53
+ end
54
+ end
55
+
56
+ task build: DISTRIBUTIONS.map { |d| "build_arch:#{d}" }
57
+
58
+ task :no_pry do
59
+ files = Dir.glob("**/**").reject { |x| x.match(/^spec|Gemfile|coverage|\.gemspec$|Rakefile/) || File.directory?(x) }
60
+ files.each do |file|
61
+ raise "Use of pry found in #{file}." if File.read(file) =~ /"pry"/
62
+ end
63
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ $LOAD_PATH << File.expand_path("../lib", __FILE__)
4
+ require "aws_assume_role/version"
5
+
6
+ PLATFORM = ENV.fetch("PLATFORM", Gem::Platform.local.os)
7
+
8
+ Gem::Specification.new do |spec|
9
+ spec.name = "aws_assume_role"
10
+ spec.version = AwsAssumeRole::VERSION
11
+ spec.authors = ["Jon Topper", "Jack Thomas", "Naadir Jeewa", "David King", "Tim Bannister", "Phil Potter", "Tom Haynes"]
12
+ spec.email = ["jon@scalefactory.com", "jack@scalefactory.com", "naadir@scalefactory.com", "tim@scalefactory.com"]
13
+
14
+ spec.description = "Used to fetch multiple AWS Role Credential "\
15
+ "Keys using different Session Keys "\
16
+ "and store them securely using Gnome Keyring "\
17
+ "or OSX keychain"
18
+ spec.summary = "Manage AWS STS credentials with MFA"
19
+ spec.homepage = "https://github.com/scalefactory/aws-assume-role"
20
+ spec.license = "Apache-2.0"
21
+
22
+ spec.files = `git ls-files -z`.split("\x0").reject { |f|
23
+ f.match(%r{^(test|spec|features)/})
24
+ }
25
+ spec.bindir = "bin"
26
+ spec.executables = spec.files.grep(%r{^bin/aws}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+ spec.platform = PLATFORM
29
+ spec.add_runtime_dependency "activesupport", "~> 4.2"
30
+ spec.add_runtime_dependency "aws-sdk", "~> 2.7"
31
+ spec.add_runtime_dependency "dry-configurable", "~> 0.5"
32
+ spec.add_runtime_dependency "dry-struct", "~> 0.1"
33
+ spec.add_runtime_dependency "dry-types", "~> 0.12"
34
+ spec.add_runtime_dependency "dry-validation", "~> 0.10"
35
+ spec.add_runtime_dependency "gli", "~> 2.15"
36
+ spec.add_runtime_dependency "highline", "~> 1.6"
37
+ spec.add_runtime_dependency "i18n", "~> 0.7"
38
+ spec.add_runtime_dependency "inifile", "~> 3.0"
39
+ spec.add_runtime_dependency "launchy", "~> 2.4"
40
+ spec.add_runtime_dependency "keyring", "~> 0.4", ">= 0.4.1"
41
+ spec.add_runtime_dependency "pastel", "~> 0.7"
42
+ spec.add_runtime_dependency "smartcard", "~> 0.5.6"
43
+ spec.add_runtime_dependency "yubioath", "~> 1.2", ">= 1.2.1"
44
+ spec.add_development_dependency "rspec", "~> 3.5"
45
+ spec.add_development_dependency "rubocop", "0.50"
46
+ spec.add_development_dependency "yard", "~> 0.9"
47
+ spec.add_development_dependency "simplecov", "~> 0.13"
48
+ spec.add_development_dependency "webmock", "~> 2.3"
49
+
50
+ case PLATFORM
51
+ when /linux|bsd/
52
+ spec.add_dependency "gir_ffi-gnome_keyring", "~> 0.0", ">= 0.0.3"
53
+ when /darwin/
54
+ spec.add_dependency "ruby-keychain", "~> 0.3", ">= 0.3.2"
55
+ end
56
+ end
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../lib/aws_assume_role/cli"
data/i18n/en.yml ADDED
@@ -0,0 +1,109 @@
1
+ en:
2
+ commands:
3
+ configure:
4
+ desc: Configure AWS
5
+ long_desc: |
6
+ Configure AWS profiles. If this command is run with no arguments,
7
+ you will be prompted for configuration values such as your AWS Access
8
+ Key Id and you AWS Secret Access Key. You can configure a named pro-
9
+ file using the --profile argument. If your config file does not exist
10
+ (the default location is ~/.aws/config), the AWS CLI will create it for
11
+ you. To keep an existing value, hit enter when prompted for the value.
12
+ When you are prompted for information, the current value will be dis-
13
+ played in [brackets]. If the config item has no value, it be displayed
14
+ as [None]. Note that the configure command only work with values from
15
+ the config file. It does not use any configuration values from envi-
16
+ ronment variables or the IAM role.
17
+
18
+ Note: The values you provide for the AWS Access Key ID and the AWS
19
+ Secret Access Key will be written to your keyring backend.
20
+ saved: Profile %s saved to %s
21
+ console:
22
+ desc: Launch the AWS console to switch to the profile role.
23
+ long_desc: |
24
+ Looks up the Role ARN in the profile, constructs the AWS console
25
+ URL and launches your browser with it. It's a convenience, doesn't
26
+ use any of the credentials.
27
+ set_environment:
28
+ desc: Export assumed credentials to your shell environment.
29
+ long_desc: |
30
+ Set up environment variables in your shell so that you can run AWS CLI
31
+ or other apps using those credentials without running aws-assume-role
32
+ again.
33
+ Supports Bourne, CSh, Fish and PowerShell.
34
+ shells:
35
+ powershell: Use `aws-assume-role environment set -s powershell -p <profile_name> | Invoke-Expression` to load into environment
36
+ others: Use `eval aws-assume-role environment set -p <profile_name>` to load into environment
37
+ fish: Use `set creds (bin/aws-assume-role environment set -s fish); eval $creds; set -e creds`
38
+ reset_environment:
39
+ desc: Delete AWS environment variables.
40
+ long_desc: |
41
+ Cleans up your shell environment by removing the following environment variables:
42
+ AWS_ACCESS_KEY_ID
43
+ AWS_SECRET_ACCESS_KEY
44
+ AWS_DEFAULT_REGION
45
+ AWS_PROFILE
46
+ AWS_ASSUME_ROLE_LOG_LEVEL
47
+ GLI_DEBUG
48
+ Supports Bourne, CSh, Fish and PowerShell.
49
+ shells:
50
+ powershell: Use `aws-assume-role environment reset -s powershell -p <profile_name> | Invoke-Expression` to load into environment
51
+ others: Use `eval aws-assume-role environment reset -p <profile_name>` to load into environment
52
+ fish: Use `set creds (bin/aws-assume-role environment reset -s fish); eval $creds; set -e creds`
53
+ run:
54
+ desc: Run a program with credentials set in the environment.
55
+ delete:
56
+ desc: Delete a profile
57
+ completed: "Profile %s deleted"
58
+ not_found: "Cannot find profile %s. Try running `aws-assume-role list`"
59
+ list:
60
+ desc: List configured profiles
61
+ migrate:
62
+ desc: Migrate a store to secure storage.
63
+ not_found: "Cannot find profile %s. Try running `aws-assume-role list`"
64
+ saved: Profile %s migrated within %s
65
+ test:
66
+ desc: Check that credentials work
67
+ output: |
68
+ Logged in as:
69
+ User: %s
70
+ Account: %s
71
+ ARN: %s
72
+ options:
73
+ aws_access_key_id: "Enter the AWS Access Key ID to use for this profile"
74
+ aws_secret_access_key: "Enter the AWS Secret Access Key to use for this profile"
75
+ region: Enter the AWS region you would like to default to
76
+ profile_name: Enter the profile name to save into configuration
77
+ mfa_token:
78
+ first_time: "Please provide an MFA token"
79
+ other_times: "Credentials have expired, please provide another MFA"
80
+ smartcard_not_supported: "Smartcard drivers not installed, see https://github.com/scalefactory/aws-assume-role/blob/master/README.md for details"
81
+ default_role: "A default role to assume (leave blank to not use)"
82
+ external_id: String provided by the external account holder to uniquely identify you.
83
+ source_profile: Which profile to use to assume this role.
84
+ role_session_name: Name to uniquely identify your session
85
+ mfa_serial: The identification number of the MFA device. Leave blank to determine dynamically at run time.
86
+ role_arn: The Amazon Resource Name (ARN) of the role to assume.
87
+ duration_seconds: Default session length
88
+ shell_type: What type of shell to use.
89
+ name_to_delete: Please type the name of the profile, i.e. %s , to continue deletion.
90
+ yubikey_oath_name: Identifier of the OATH / TOTP secret stored on the yubikey.
91
+ program_description: "A tool for AWS credential management"
92
+ errors:
93
+ NoSuchProfileError: Profile %s not found in shared configuration.
94
+ SmartcardException: No YubiKey found!
95
+ MissingCredentialsError: No credentials found!
96
+ rules:
97
+ profile:
98
+ filled?: --profile must be specified.
99
+ role-arn:
100
+ format?: "--role-arn must be specified as an ARN in the format `arn:aws:iam::account-id:role/role-name`"
101
+ filled?: --role-arn is required.
102
+ serial-number:
103
+ format?: "--mfa-serial must be specified as an ARN in the format `arn:aws:iam::account-id:mfa/virtual-device-name`"
104
+ filled?: --mfa-serial is required.
105
+ region:
106
+ format?: "--region must be a valid AWS Standard, China or GovCloud region"
107
+ filled?: --region is required
108
+ role_specification:
109
+ filled?: "Either specify --profile OR (--role-arn AND --role-session-name, or neither)"
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "aws_assume_role/store/shared_config_with_keyring"
4
+ require_relative "aws_assume_role/credentials/factories/default_chain_provider"
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "includes"
4
+ require_relative "ui"
5
+ require_relative "logging"
6
+
7
+ module AwsAssumeRole::Cli
8
+ include AwsAssumeRole
9
+ include AwsAssumeRole::Ui
10
+ include AwsAssumeRole::Logging
11
+ logger.debug "Bootstrapping"
12
+ include GLI::DSL
13
+ include GLI::App
14
+ extend self # rubocop:disable Style/ModuleFunction
15
+
16
+ commands_from File.join(File.realpath(__dir__), "cli", "commands")
17
+ program_desc t "program_description"
18
+
19
+ exit run(ARGV)
20
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "includes"
4
+ require_relative "../../profile_configuration"
5
+
6
+ class AwsAssumeRole::Cli::Actions::AbstractAction
7
+ include AwsAssumeRole
8
+ include AwsAssumeRole::Types
9
+ include AwsAssumeRole::Ui
10
+ include AwsAssumeRole::Logging
11
+ CommandSchema = proc { raise "CommandSchema Not implemented" }
12
+
13
+ def initialize(global_options, options, args)
14
+ config = ProfileConfiguration.new_from_cli(global_options, options, args)
15
+ logger.debug "Config initialized with #{config.to_hash}"
16
+ result = validate_options(config.to_hash)
17
+ logger.debug "Config validated as #{result.to_hash}"
18
+ result.success? ? act_on(config) : Ui.show_validation_errors(result)
19
+ end
20
+
21
+ private
22
+
23
+ def try_for_credentials(config)
24
+ @provider ||= AwsAssumeRole::Credentials::Factories::DefaultChainProvider.new(config.to_hash)
25
+ creds = @provider.resolve(nil_with_role_not_set: true)
26
+ logger.debug "Got credentials #{creds}"
27
+ return creds unless creds.nil?
28
+ rescue Smartcard::PCSC::Exception
29
+ error t("errors.SmartcardException")
30
+ exit 403
31
+ rescue NoMethodError
32
+ error t("errors.MissingCredentialsError")
33
+ exit 404
34
+ end
35
+
36
+ def resolved_region
37
+ @provider.region
38
+ end
39
+
40
+ def resolved_profile
41
+ @provider.profile
42
+ end
43
+
44
+ def validate_options(options)
45
+ command_schema = self.class::CommandSchema
46
+ ::Dry::Validation.Schema do
47
+ configure { config.messages = :i18n }
48
+ instance_eval(&command_schema)
49
+ end.call(options)
50
+ end
51
+
52
+ def prompt_for_option(key, option_name, validator, fmt: nil)
53
+ text_lookup = t("options.#{key}")
54
+ text = fmt.nil? ? text_lookup : format(text_lookup, fmt)
55
+ Ui.ask_with_validation(option_name, text) { instance_eval(&validator) }
56
+ end
57
+
58
+ def act_on(_options)
59
+ raise "Act On Not Implemented"
60
+ end
61
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "abstract_action"
4
+ require_relative "../../store/shared_config_with_keyring"
5
+
6
+ class AwsAssumeRole::Cli::Actions::ConfigureProfile < AwsAssumeRole::Cli::Actions::AbstractAction
7
+ CommandSchema = proc do
8
+ required(:profile)
9
+ optional(:region) { filled? > format?(REGION_REGEX) }
10
+ optional(:mfa_serial)
11
+ optional(:profile_name)
12
+ optional(:yubikey_oath_name)
13
+ end
14
+
15
+ def act_on(config)
16
+ new_hash = config.to_h
17
+ profile = config.profile || prompt_for_option(:profile_name, "profile", proc { filled? })
18
+ new_hash[:region] = prompt_for_option(:region, "region", proc { filled? > format?(REGION_REGEX) })
19
+ new_hash[:aws_access_key_id] = prompt_for_option(:aws_access_key_id, "aws_access_key_id", ACCESS_KEY_VALIDATOR)
20
+ new_hash[:aws_secret_access_key] = prompt_for_option(:aws_secret_access_key, "aws_secret_access_key", proc { filled? })
21
+ AwsAssumeRole.shared_config.save_profile(profile, new_hash)
22
+ out format(t("commands.configure.saved"), profile, AwsAssumeRole.shared_config.config_path)
23
+ end
24
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "abstract_action"
4
+
5
+ class AwsAssumeRole::Cli::Actions::ConfigureRoleAssumption < AwsAssumeRole::Cli::Actions::AbstractAction
6
+ CommandSchema = proc do
7
+ required(:profile)
8
+ required(:source_profile) { str? }
9
+ optional(:region) { filled? > format?(REGION_REGEX) }
10
+ optional(:serial_number) { filled? > format?(MFA_REGEX) }
11
+ required(:role_session_name).filled?
12
+ required(:role_arn) { filled? & format?(ROLE_REGEX) }
13
+ required(:external_id).filled?
14
+ required(:duration_seconds).filled?
15
+ optional(:yubikey_oath_name)
16
+ end
17
+
18
+ def act_on(config)
19
+ AwsAssumeRole.shared_config.save_profile(config.profile, config.to_h.compact)
20
+ out format(t("commands.configure.saved"), config.profile, AwsAssumeRole.shared_config.config_path)
21
+ end
22
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "includes"
4
+ require_relative "../../runner"
5
+ require "cgi"
6
+ require "json"
7
+
8
+ class AwsAssumeRole::Cli::Actions::Console < AwsAssumeRole::Cli::Actions::AbstractAction
9
+ include AwsAssumeRole::Ui
10
+ include AwsAssumeRole::Logging
11
+
12
+ FEDERATION_URL = "https://signin.aws.amazon.com/federation".freeze
13
+ CONSOLE_URL = "https://console.aws.amazon.com".freeze
14
+ GENERIC_SIGNIN_URL = "https://signin.aws.amazon.com/console".freeze
15
+ SIGNIN_URL = [FEDERATION_URL, "?Action=getSigninToken", "&Session=%s"].join
16
+ LOGIN_URL = [FEDERATION_URL, "?Action=login", "&Destination=%s", "&SigninToken=%s"].join
17
+
18
+ CommandSchema = proc do
19
+ required(:profile).maybe
20
+ optional(:region) { filled? > format?(REGION_REGEX) }
21
+ optional(:serial_number) { filled? > format?(MFA_REGEX) }
22
+ required(:role_arn).maybe
23
+ required(:role_session_name).maybe
24
+ required(:duration_seconds).maybe
25
+ rule(role_specification: %i[profile role_arn role_session_name duration_seconds]) do |p, r, s, d|
26
+ (p.filled? | p.empty? & r.filled?) & (r.filled? > s.filled? & d.filled?)
27
+ end
28
+ end
29
+
30
+ def try_federation(config)
31
+ credentials = try_for_credentials config.to_h
32
+ return unless credentials.set?
33
+ session = session_json(credentials)
34
+ signin_url = format SIGNIN_URL, CGI.escape(session)
35
+ sso_token = JSON.parse(URI.parse(signin_url).read)["SigninToken"]
36
+ format LOGIN_URL, CGI.escape(CONSOLE_URL), CGI.escape(sso_token)
37
+ rescue OpenURI::HTTPError
38
+ error "Error getting federated session, forming simple switch URL instead"
39
+ end
40
+
41
+ def session_json(credentials)
42
+ {
43
+ sessionId: credentials.credentials.access_key_id,
44
+ sessionKey: credentials.credentials.secret_access_key,
45
+ sessionToken: credentials.credentials.session_token,
46
+ }.to_json
47
+ end
48
+
49
+ def try_switch_url(config)
50
+ profile = AwsAssumeRole.shared_config.determine_profile(profile_name: config.profile)
51
+ config_section = AwsAssumeRole.shared_config.parsed_config[profile]
52
+ raise Aws::Errors::NoSuchProfileError if config_section.nil?
53
+ resolved_role_arn = config.role_arn || config_section.fetch("role_arn", nil)
54
+ return unless resolved_role_arn
55
+ components = resolved_role_arn.split(":")
56
+ account = components[4]
57
+ role = components[5].split("/").last
58
+ display_name = config.profile || "#{account}_#{role}"
59
+ format "https://signin.aws.amazon.com/switchrole?account=%s&roleName=%s&displayName=%s", account, role, display_name
60
+ end
61
+
62
+ def act_on(config)
63
+ final_url = try_federation(config) || try_switch_url(config) || CONSOLE_URL
64
+ Launchy.open final_url
65
+ rescue KeyError, Aws::Errors::NoSuchProfileError
66
+ error format(t("errors.NoSuchProfileError"), config.profile)
67
+ rescue Aws::Errors::MissingCredentialsError
68
+ error t("errors.MissingCredentialsError")
69
+ end
70
+ end