Class: Oneaws::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/oneaws/client.rb

Defined Under Namespace

Classes: MfaDeviceNotFoundError, SamlRequestError

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/oneaws/client.rb', line 10

def initialize
  @onelogin = OneLogin::Api::Client.new({
    client_id: ENV['ONELOGIN_CLIENT_ID'],
    client_secret: ENV['ONELOGIN_CLIENT_SECRET'],
    region: ENV['ONELOGIN_REGION'] || 'us',
  })

  @aws = Aws::STS::Client.new(
    credentials: nil,
    region: ENV['AWS_REGION'] || 'ap-northeast-1',
  )
end

Instance Method Details

#issue_credential(options, otp = nil) ⇒ Object



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
# File 'lib/oneaws/client.rb', line 23

def issue_credential(options, otp = nil)
  username = options[:username]
  password = options[:password]
  app_id = options[:app_id]
  subdomain = options[:subdomain]
  response = @onelogin.get_saml_assertion(username, password, app_id, subdomain)
  if response.nil?
    raise SamlRequestError.new("#{@onelogin.error} #{@onelogin.error_description}")
  end

  mfa = response.mfa

  if mfa # mfa required
    mfa_device = select_mfa_device(mfa)
    
    device_types_that_do_not_require_token = [
      "OneLogin Protect"
    ]

    otp_token = if device_types_that_do_not_require_token.include?(mfa_device.type)
      nil
    elsif otp
      otp
    else
      print "input OTP of #{mfa_device.type}: "
      STDIN.noecho(&:gets)
    end

    response = @onelogin.get_saml_assertion_verifying(app_id, mfa_device.id, mfa.state_token, otp_token, nil, false)
    
    if response.nil?
      raise SamlRequestError.new("#{@onelogin.error} #{@onelogin.error_description}")
    end

    while response.type != "success" do
      sleep 1
      response = @onelogin.get_saml_assertion_verifying(app_id, mfa_device.id, mfa.state_token, nil, nil, true)
      if response.nil?
        raise SamlRequestError.new("#{@onelogin.error} #{@onelogin.error_description}")
      end
    end
  end

  saml_assertion = response.saml_response

  params = {
    duration_seconds: (ENV['DURATION_SECONDS'] || 3600).to_i,
    principal_arn: ENV['AWS_PRINCIPAL_ARN'],
    role_arn: ENV['AWS_ROLE_ARN'],
    saml_assertion: saml_assertion,
  }
  @aws.assume_role_with_saml(params)[:credentials]
end