Class: Heroku::Auth

Inherits:
Object
  • Object
show all
Extended by:
Helpers
Defined in:
lib/heroku/auth.rb

Class Attribute Summary collapse

Class Method Summary collapse

Methods included from Helpers

action, app_owner, ask, confirm, confirm_command, create_git_remote, debug, debugging?, default_org_host, deprecate, display, display_header, display_object, display_row, display_table, error, error_log, error_log_path, error_with_failure, error_with_failure=, extended, extended_into, fail, format_bytes, format_date, format_error, format_with_bang, get_terminal_environment, git, has_git?, has_git_remote?, has_http_git_entry_in_netrc, home_directory, hprint, hputs, included, included_into, json_decode, json_encode, launchy, line_formatter, longest, org?, org_host, output_with_bang, quantify, redisplay, retry_on_exception, run_command, running_on_a_mac?, running_on_windows?, set_buffer, shell, spinner, status, stderr_print, stderr_puts, string_distance, styled_array, styled_error, styled_hash, styled_header, suggestion, time_ago, truncate, update_git_remote, warn_if_using_jruby, with_tty

Class Attribute Details

.credentialsObject

Returns the value of attribute credentials


12
13
14
# File 'lib/heroku/auth.rb', line 12

def credentials
  @credentials
end

Class Method Details

.apiObject


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/heroku/auth.rb', line 14

def api
  @api ||= begin
    debug "Using API with key: #{password[0,6]}..."
    api = Heroku::API.new(default_params.merge(:api_key => password))

    def api.request(params, &block)
      response = super
      if response.headers.has_key?('X-Heroku-Warning')
        Heroku::Command.warnings.concat(response.headers['X-Heroku-Warning'].split("\n"))
      end
      response
    end

    api
  end
end

.api_key(user = get_credentials[0], password = get_credentials[1]) ⇒ Object


85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/heroku/auth.rb', line 85

def api_key(user=get_credentials[0], password=get_credentials[1])
  @api ||= Heroku::API.new(default_params)
  api_key = @api.(user, password).body["api_key"]
  @api = nil
  api_key
rescue Heroku::API::Errors::Forbidden => e
  if e.response.headers.has_key?("Heroku-Two-Factor-Required")
    ask_for_second_factor
    retry
  end
rescue Heroku::API::Errors::Unauthorized => e
  id = json_decode(e.response.body)["id"]
  raise if id != "invalid_two_factor_code"
  delete_credentials
  display "Authentication failed due to an invalid two-factor code."
  display "Please check your code was typed correctly and that your"
  display "authenticator's time keeping is accurate."
  exit 1
end

.ask_for_and_save_credentialsObject


264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/heroku/auth.rb', line 264

def ask_for_and_save_credentials
  warn "WARNING: heroku-accounts plugin is installed. This plugin is known to have problems with HTTP Git." if defined?(Heroku::Command::Accounts)
  @credentials = ask_for_credentials
  debug "Logged in as #{@credentials[0]} with key: #{@credentials[1][0,6]}..."
  write_credentials
  check
  @credentials
rescue Heroku::API::Errors::NotFound, Heroku::API::Errors::Unauthorized => e
  delete_credentials
  display "Authentication failed."
  warn "WARNING: HEROKU_API_KEY is set to an invalid key." if ENV['HEROKU_API_KEY']
  retry if retry_login?
  exit 1
rescue => e
  delete_credentials
  raise e
end

.ask_for_credentialsObject


208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/heroku/auth.rb', line 208

def ask_for_credentials
  puts "Enter your Heroku credentials."

  print "Email: "
  user = ask

  print "Password (typing will be hidden): "
  password = running_on_windows? ? ask_for_password_on_windows : ask_for_password
  HTTPInstrumentor.filter_parameter(password)

  [user, api_key(user, password)]
end

.ask_for_passwordObject


253
254
255
256
257
258
259
260
261
262
# File 'lib/heroku/auth.rb', line 253

def ask_for_password
  begin
    echo_off
    password = ask
    puts
  ensure
    echo_on
  end
  return password
end

.ask_for_password_on_windowsObject


235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/heroku/auth.rb', line 235

def ask_for_password_on_windows
  require "Win32API"
  char = nil
  password = ''

  while char = Win32API.new("crtdll", "_getch", [ ], "L").Call do
    break if char == 10 || char == 13 # received carriage return or newline
    if char == 127 || char == 8 # backspace and delete
      password.slice!(-1, 1)
    else
      # windows might throw a -1 at us so make sure to handle RangeError
      (password << char.chr) rescue RangeError
    end
  end
  puts
  return password
end

.ask_for_second_factorObject


221
222
223
224
# File 'lib/heroku/auth.rb', line 221

def ask_for_second_factor
  $stderr.print "Two-factor code: "
  api.second_factor = ask
end

.associate_key(key) ⇒ Object


332
333
334
335
336
337
338
339
340
# File 'lib/heroku/auth.rb', line 332

def associate_key(key)
  action("Uploading SSH public key #{key}") do
    if File.exists?(key)
      api.post_key(File.read(key))
    else
      error("Could not upload SSH public key: key file '" + key + "' does not exist")
    end
  end
end

.associate_or_generate_ssh_keyObject


282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/heroku/auth.rb', line 282

def associate_or_generate_ssh_key
  unless File.exists?("#{home_directory}/.ssh/id_rsa.pub")
    display "Could not find an existing public key at ~/.ssh/id_rsa.pub"
    display "Would you like to generate one? [Yn] ", false
    unless ask.strip.downcase =~ /^n/
      display "Generating new SSH public key."
      generate_ssh_key("#{home_directory}/.ssh/id_rsa")
      associate_key("#{home_directory}/.ssh/id_rsa.pub")
      return
    end
  end

  chosen = ssh_prompt
  associate_key(chosen) if chosen
end

.base_host(host) ⇒ Object


348
349
350
351
352
# File 'lib/heroku/auth.rb', line 348

def base_host(host)
  parts = URI.parse(full_host(host)).host.split(".")
  return parts.first if parts.size == 1
  parts[-2..-1].join(".")
end

.checkObject

just a stub; will raise if not authenticated


49
50
51
# File 'lib/heroku/auth.rb', line 49

def check
  api.get_user
end

.clientObject


31
32
33
34
35
36
37
# File 'lib/heroku/auth.rb', line 31

def client
  @client ||= begin
    client = Heroku::Client.new(user, password, host)
    client.on_warning { |msg| self.display("\n#{msg}\n\n") }
    client
  end
end

.default_hostObject


53
54
55
# File 'lib/heroku/auth.rb', line 53

def default_host
  "heroku.com"
end

.delete_credentialsObject


109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/heroku/auth.rb', line 109

def delete_credentials
  if File.exists?(legacy_credentials_path)
    FileUtils.rm_f(legacy_credentials_path)
  end
  if netrc
    subdomains.each do |sub|
      netrc.delete("#{sub}.#{host}")
    end
    netrc.save
  end
  @api, @client, @credentials = nil, nil
end

.echo_offObject


196
197
198
199
200
# File 'lib/heroku/auth.rb', line 196

def echo_off
  with_tty do
    system "stty -echo"
  end
end

.echo_onObject


202
203
204
205
206
# File 'lib/heroku/auth.rb', line 202

def echo_on
  with_tty do
    system "stty echo"
  end
end

.full_host(*args) ⇒ Object


354
355
356
357
358
# File 'lib/heroku/auth.rb', line 354

def full_host(*args)
  # backwards compat for when this took an arg
  h = args.first || host
  (h =~ /^http/) ? h : "https://api.#{h}"
end

.full_host_uriObject


360
361
362
# File 'lib/heroku/auth.rb', line 360

def full_host_uri
  URI.parse(full_host)
end

.generate_ssh_key(keyfile) ⇒ Object


323
324
325
326
327
328
329
330
# File 'lib/heroku/auth.rb', line 323

def generate_ssh_key(keyfile)
  ssh_dir = File.dirname(keyfile)
  FileUtils.mkdir_p ssh_dir, :mode => 0700
  output = `ssh-keygen -t rsa -N "" -f \"#{keyfile}\" 2>&1`
  if ! $?.success?
    error("Could not generate key: #{output}")
  end
end

.get_credentialsObject

:nodoc:


105
106
107
# File 'lib/heroku/auth.rb', line 105

def get_credentials    # :nodoc:
  @credentials ||= (read_credentials || ask_for_and_save_credentials)
end

.git_hostObject


61
62
63
# File 'lib/heroku/auth.rb', line 61

def git_host
  ENV['HEROKU_GIT_HOST'] || host
end

.hostObject


65
66
67
# File 'lib/heroku/auth.rb', line 65

def host
  ENV['HEROKU_HOST'] || default_host
end

.http_git_hostObject


57
58
59
# File 'lib/heroku/auth.rb', line 57

def http_git_host
  ENV['HEROKU_HTTP_GIT_HOST'] || "git.#{host}"
end

.legacy_credentials_pathObject


122
123
124
125
126
127
128
# File 'lib/heroku/auth.rb', line 122

def legacy_credentials_path
  if host == default_host
    "#{home_directory}/.heroku/credentials"
  else
    "#{home_directory}/.heroku/credentials.#{CGI.escape(host)}"
  end
end

.loginObject


39
40
41
42
# File 'lib/heroku/auth.rb', line 39

def 
  delete_credentials
  get_credentials
end

.logoutObject


44
45
46
# File 'lib/heroku/auth.rb', line 44

def logout
  delete_credentials
end

.netrcObject

:nodoc:


140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/heroku/auth.rb', line 140

def netrc   # :nodoc:
  @netrc ||= begin
    File.exists?(netrc_path) && Netrc.read(netrc_path)
  rescue => error
    case error.message
    when /^Permission bits for/
      abort("#{error.message}.\nYou should run `chmod 0600 #{netrc_path}` so that your credentials are NOT accessible by others.")
    when /EACCES/
      error("Error reading #{netrc_path}\n#{error.message}\nMake sure this user can read/write this file.")
    else
      error("Error reading #{netrc_path}\n#{error.message}\nYou may need to delete this file and run `heroku login` to recreate it.")
    end
  end
end

.netrc_pathObject


130
131
132
133
134
135
136
137
138
# File 'lib/heroku/auth.rb', line 130

def netrc_path
  default = Netrc.default_path
  encrypted = default + ".gpg"
  if File.exists?(encrypted)
    encrypted
  else
    default
  end
end

.passwordObject

:nodoc:


81
82
83
# File 'lib/heroku/auth.rb', line 81

def password    # :nodoc:
  get_credentials[1]
end

.preauthObject


226
227
228
229
230
231
232
233
# File 'lib/heroku/auth.rb', line 226

def preauth
  if Heroku.app_name
    second_factor = ask_for_second_factor
    api.request(:method => :put,
                :path => "/apps/#{Heroku.app_name}/pre-authorizations",
                :headers => {"Heroku-Two-Factor-Code" => second_factor})
  end
end

.read_credentialsObject


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
# File 'lib/heroku/auth.rb', line 155

def read_credentials
  if ENV['HEROKU_API_KEY']
    ['', ENV['HEROKU_API_KEY']]
  else
    # convert legacy credentials to netrc
    if File.exists?(legacy_credentials_path)
      @api, @client = nil
      @credentials = File.read(legacy_credentials_path).split("\n")
      write_credentials
      FileUtils.rm_f(legacy_credentials_path)
    end

    # read netrc credentials if they exist
    if netrc
      netrc_host = full_host_uri.host

      # force migration of long api tokens (80 chars) to short ones (40)
      # #write_credentials rewrites both api.* and code.*
      credentials = netrc[netrc_host]
      if credentials && credentials[1].length > 40
        @credentials = [ credentials[0], credentials[1][0,40] ]
        write_credentials
      end

      netrc[netrc_host]
    end
  end
end

.reauthorizeObject


73
74
75
# File 'lib/heroku/auth.rb', line 73

def reauthorize
  @credentials = ask_for_and_save_credentials
end

.retry_login?Boolean

Returns:

  • (Boolean)

342
343
344
345
346
# File 'lib/heroku/auth.rb', line 342

def retry_login?
  @login_attempts ||= 0
  @login_attempts += 1
  @login_attempts < 3
end

.ssh_promptObject


298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/heroku/auth.rb', line 298

def ssh_prompt
  public_keys = Dir.glob("#{home_directory}/.ssh/*.pub").sort
  case public_keys.length
  when 0
    error("No SSH keys found")
    return nil
  when 1
    display "Found an SSH public key at #{public_keys.first}"
    display "Would you like to upload it to Heroku? [Yn] ", false
    return ask.strip.downcase =~ /^n/ ? nil : public_keys.first
  else
    display "Found the following SSH public keys:"
    public_keys.each_with_index do |key, index|
      display "#{index+1}) #{File.basename(key)}"
    end
    display "Which would you like to use with your Heroku account? ", false
    choice = ask.to_i - 1
    chosen = public_keys[choice]
    if choice == -1 || chosen.nil?
      error("Invalid choice")
    end
    return chosen
  end
end

.subdomainsObject


69
70
71
# File 'lib/heroku/auth.rb', line 69

def subdomains
  %w(api git)
end

.userObject

:nodoc:


77
78
79
# File 'lib/heroku/auth.rb', line 77

def user    # :nodoc:
  get_credentials[0]
end

.verify_host?(host) ⇒ Boolean

Returns:

  • (Boolean)

364
365
366
367
# File 'lib/heroku/auth.rb', line 364

def verify_host?(host)
  return false if ENV["HEROKU_SSL_VERIFY"] == "disable"
  base_host(host) == "heroku.com"
end

.write_credentialsObject


184
185
186
187
188
189
190
191
192
193
194
# File 'lib/heroku/auth.rb', line 184

def write_credentials
  FileUtils.mkdir_p(File.dirname(netrc_path))
  FileUtils.touch(netrc_path)
  unless running_on_windows?
    FileUtils.chmod(0600, netrc_path)
  end
  subdomains.each do |sub|
    netrc["#{sub}.#{host}"] = self.credentials
  end
  netrc.save
end