Added HTTP Proxy support
[arvados.git] / lib / google / api_client.rb
1 # Copyright 2010 Google Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 require 'faraday'
17 require 'multi_json'
18 require 'compat/multi_json'
19 require 'stringio'
20 require 'retriable'
21
22 require 'google/api_client/version'
23 require 'google/api_client/logging'
24 require 'google/api_client/errors'
25 require 'google/api_client/environment'
26 require 'google/api_client/discovery'
27 require 'google/api_client/request'
28 require 'google/api_client/reference'
29 require 'google/api_client/result'
30 require 'google/api_client/media'
31 require 'google/api_client/service_account'
32 require 'google/api_client/batch'
33 require 'google/api_client/gzip'
34 require 'google/api_client/client_secrets'
35 require 'google/api_client/railtie' if defined?(Rails::Railtie)
36
37 module Google
38
39   ##
40   # This class manages APIs communication.
41   class APIClient
42     include Google::APIClient::Logging
43     
44     ##
45     # Creates a new Google API client.
46     #
47     # @param [Hash] options The configuration parameters for the client.
48     # @option options [Symbol, #generate_authenticated_request] :authorization
49     #   (:oauth_1)
50     #   The authorization mechanism used by the client.  The following
51     #   mechanisms are supported out-of-the-box:
52     #   <ul>
53     #     <li><code>:two_legged_oauth_1</code></li>
54     #     <li><code>:oauth_1</code></li>
55     #     <li><code>:oauth_2</code></li>
56     #   </ul>
57     # @option options [Boolean] :auto_refresh_token (true)
58     #   The setting that controls whether or not the api client attempts to
59     #   refresh authorization when a 401 is hit in #execute. If the token does 
60     #   not support it, this option is ignored.
61     # @option options [String] :application_name
62     #   The name of the application using the client.
63     # @option options [String] :application_version
64     #   The version number of the application using the client.
65     # @option options [String] :user_agent
66     #   ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
67     #   The user agent used by the client.  Most developers will want to
68     #   leave this value alone and use the `:application_name` option instead.
69     # @option options [String] :host ("www.googleapis.com")
70     #   The API hostname used by the client. This rarely needs to be changed.
71     # @option options [String] :port (443)
72     #   The port number used by the client. This rarely needs to be changed.
73     # @option options [String] :discovery_path ("/discovery/v1")
74     #   The discovery base path. This rarely needs to be changed.
75     # @option options [String] :ca_file
76     #   Optional set of root certificates to use when validating SSL connections.
77     #   By default, a bundled set of trusted roots will be used.
78     def initialize(options={})
79       logger.debug { "#{self.class} - Initializing client with options #{options}" }
80       
81       # Normalize key to String to allow indifferent access.
82       options = options.inject({}) do |accu, (key, value)|
83         accu[key.to_sym] = value
84         accu
85       end
86       # Almost all API usage will have a host of 'www.googleapis.com'.
87       self.host = options[:host] || 'www.googleapis.com'
88       self.port = options[:port] || 443
89       self.discovery_path = options[:discovery_path] || '/discovery/v1'
90
91       # Most developers will want to leave this value alone and use the
92       # application_name option.
93       if options[:application_name]
94         app_name = options[:application_name]
95         app_version = options[:application_version]
96         application_string = "#{app_name}/#{app_version || '0.0.0'}"
97       else
98         logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
99       end
100
101       proxy = options[:proxy] || Object::ENV["http_proxy"]
102
103       self.user_agent = options[:user_agent] || (
104         "#{application_string} " +
105         "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} #{ENV::OS_VERSION} (gzip)"
106       ).strip
107       # The writer method understands a few Symbols and will generate useful
108       # default authentication mechanisms.
109       self.authorization =
110         options.key?(:authorization) ? options[:authorization] : :oauth_2
111       self.auto_refresh_token = options.fetch(:auto_refresh_token) { true }
112       self.key = options[:key]
113       self.user_ip = options[:user_ip]
114       self.retries = options.fetch(:retries) { 0 }
115       @discovery_uris = {}
116       @discovery_documents = {}
117       @discovered_apis = {}
118       ca_file = options[:ca_file] || File.expand_path('../../cacerts.pem', __FILE__)
119       self.connection = Faraday.new do |faraday|
120         faraday.response :gzip
121         faraday.options.params_encoder = Faraday::FlatParamsEncoder
122         faraday.ssl.ca_file = ca_file
123         faraday.ssl.verify = true
124         faraday.proxy proxy
125         faraday.adapter Faraday.default_adapter
126       end
127       return self
128     end
129
130     ##
131     # Returns the authorization mechanism used by the client.
132     #
133     # @return [#generate_authenticated_request] The authorization mechanism.
134     attr_reader :authorization
135
136     ##
137     # Sets the authorization mechanism used by the client.
138     #
139     # @param [#generate_authenticated_request] new_authorization
140     #   The new authorization mechanism.
141     def authorization=(new_authorization)
142       case new_authorization
143       when :oauth_1, :oauth
144         require 'signet/oauth_1/client'
145         # NOTE: Do not rely on this default value, as it may change
146         new_authorization = Signet::OAuth1::Client.new(
147           :temporary_credential_uri =>
148             'https://www.google.com/accounts/OAuthGetRequestToken',
149           :authorization_uri =>
150             'https://www.google.com/accounts/OAuthAuthorizeToken',
151           :token_credential_uri =>
152             'https://www.google.com/accounts/OAuthGetAccessToken',
153           :client_credential_key => 'anonymous',
154           :client_credential_secret => 'anonymous'
155         )
156       when :two_legged_oauth_1, :two_legged_oauth
157         require 'signet/oauth_1/client'
158         # NOTE: Do not rely on this default value, as it may change
159         new_authorization = Signet::OAuth1::Client.new(
160           :client_credential_key => nil,
161           :client_credential_secret => nil,
162           :two_legged => true
163         )
164       when :oauth_2
165         require 'signet/oauth_2/client'
166         # NOTE: Do not rely on this default value, as it may change
167         new_authorization = Signet::OAuth2::Client.new(
168           :authorization_uri =>
169             'https://accounts.google.com/o/oauth2/auth',
170           :token_credential_uri =>
171             'https://accounts.google.com/o/oauth2/token'
172         )
173       when nil
174         # No authorization mechanism
175       else
176         if !new_authorization.respond_to?(:generate_authenticated_request)
177           raise TypeError,
178             'Expected authorization mechanism to respond to ' +
179             '#generate_authenticated_request.'
180         end
181       end
182       @authorization = new_authorization
183       return @authorization
184     end
185
186     ##
187     # Default Faraday/HTTP connection.
188     #
189     # @return [Faraday::Connection]
190     attr_accessor :connection
191
192     ##
193     # The setting that controls whether or not the api client attempts to
194     # refresh authorization when a 401 is hit in #execute. 
195     #
196     # @return [Boolean]
197     attr_accessor :auto_refresh_token
198
199     ##
200     # The application's API key issued by the API console.
201     #
202     # @return [String] The API key.
203     attr_accessor :key
204
205     ##
206     # The IP address of the user this request is being performed on behalf of.
207     #
208     # @return [String] The user's IP address.
209     attr_accessor :user_ip
210
211     ##
212     # The user agent used by the client.
213     #
214     # @return [String]
215     #   The user agent string used in the User-Agent header.
216     attr_accessor :user_agent
217
218     ##
219     # The API hostname used by the client.
220     #
221     # @return [String]
222     #   The API hostname. Should almost always be 'www.googleapis.com'.
223     attr_accessor :host
224
225     ##
226     # The port number used by the client.
227     #
228     # @return [String]
229     #   The port number. Should almost always be 443.
230     attr_accessor :port
231
232     ##
233     # The base path used by the client for discovery.
234     #
235     # @return [String]
236     #   The base path. Should almost always be '/discovery/v1'.
237     attr_accessor :discovery_path
238
239     ##
240     # Number of times to retry on recoverable errors
241     # 
242     # @return [FixNum]
243     #  Number of retries
244     attr_accessor :retries
245
246     ##
247     # Returns the URI for the directory document.
248     #
249     # @return [Addressable::URI] The URI of the directory document.
250     def directory_uri
251       return resolve_uri(self.discovery_path + '/apis')
252     end
253
254     ##
255     # Manually registers a URI as a discovery document for a specific version
256     # of an API.
257     #
258     # @param [String, Symbol] api The API name.
259     # @param [String] version The desired version of the API.
260     # @param [Addressable::URI] uri The URI of the discovery document.
261     def register_discovery_uri(api, version, uri)
262       api = api.to_s
263       version = version || 'v1'
264       @discovery_uris["#{api}:#{version}"] = uri
265     end
266
267     ##
268     # Returns the URI for the discovery document.
269     #
270     # @param [String, Symbol] api The API name.
271     # @param [String] version The desired version of the API.
272     # @return [Addressable::URI] The URI of the discovery document.
273     def discovery_uri(api, version=nil)
274       api = api.to_s
275       version = version || 'v1'
276       return @discovery_uris["#{api}:#{version}"] ||= (
277         resolve_uri(
278           self.discovery_path + '/apis/{api}/{version}/rest',
279           'api' => api,
280           'version' => version
281         )
282       )
283     end
284
285     ##
286     # Manually registers a pre-loaded discovery document for a specific version
287     # of an API.
288     #
289     # @param [String, Symbol] api The API name.
290     # @param [String] version The desired version of the API.
291     # @param [String, StringIO] discovery_document
292     #   The contents of the discovery document.
293     def register_discovery_document(api, version, discovery_document)
294       api = api.to_s
295       version = version || 'v1'
296       if discovery_document.kind_of?(StringIO)
297         discovery_document.rewind
298         discovery_document = discovery_document.string
299       elsif discovery_document.respond_to?(:to_str)
300         discovery_document = discovery_document.to_str
301       else
302         raise TypeError,
303           "Expected String or StringIO, got #{discovery_document.class}."
304       end
305       @discovery_documents["#{api}:#{version}"] =
306         MultiJson.load(discovery_document)
307     end
308
309     ##
310     # Returns the parsed directory document.
311     #
312     # @return [Hash] The parsed JSON from the directory document.
313     def directory_document
314       return @directory_document ||= (begin
315         response = self.execute!(
316           :http_method => :get,
317           :uri => self.directory_uri,
318           :authenticated => false
319         )
320         response.data
321       end)
322     end
323
324     ##
325     # Returns the parsed discovery document.
326     #
327     # @param [String, Symbol] api The API name.
328     # @param [String] version The desired version of the API.
329     # @return [Hash] The parsed JSON from the discovery document.
330     def discovery_document(api, version=nil)
331       api = api.to_s
332       version = version || 'v1'
333       return @discovery_documents["#{api}:#{version}"] ||= (begin
334         response = self.execute!(
335           :http_method => :get,
336           :uri => self.discovery_uri(api, version),
337           :authenticated => false
338         )
339         response.data
340       end)
341     end
342
343     ##
344     # Returns all APIs published in the directory document.
345     #
346     # @return [Array] The list of available APIs.
347     def discovered_apis
348       @directory_apis ||= (begin
349         document_base = self.directory_uri
350         if self.directory_document && self.directory_document['items']
351           self.directory_document['items'].map do |discovery_document|
352             Google::APIClient::API.new(
353               document_base,
354               discovery_document
355             )
356           end
357         else
358           []
359         end
360       end)
361     end
362
363     ##
364     # Returns the service object for a given service name and service version.
365     #
366     # @param [String, Symbol] api The API name.
367     # @param [String] version The desired version of the API.
368     #
369     # @return [Google::APIClient::API] The service object.
370     def discovered_api(api, version=nil)
371       if !api.kind_of?(String) && !api.kind_of?(Symbol)
372         raise TypeError,
373           "Expected String or Symbol, got #{api.class}."
374       end
375       api = api.to_s
376       version = version || 'v1'
377       return @discovered_apis["#{api}:#{version}"] ||= begin
378         document_base = self.discovery_uri(api, version)
379         discovery_document = self.discovery_document(api, version)
380         if document_base && discovery_document
381           Google::APIClient::API.new(
382             document_base,
383             discovery_document
384           )
385         else
386           nil
387         end
388       end
389     end
390
391     ##
392     # Returns the method object for a given RPC name and service version.
393     #
394     # @param [String, Symbol] rpc_name The RPC name of the desired method.
395     # @param [String, Symbol] api The API the method is within.
396     # @param [String] version The desired version of the API.
397     #
398     # @return [Google::APIClient::Method] The method object.
399     def discovered_method(rpc_name, api, version=nil)
400       if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
401         raise TypeError,
402           "Expected String or Symbol, got #{rpc_name.class}."
403       end
404       rpc_name = rpc_name.to_s
405       api = api.to_s
406       version = version || 'v1'
407       service = self.discovered_api(api, version)
408       if service.to_h[rpc_name]
409         return service.to_h[rpc_name]
410       else
411         return nil
412       end
413     end
414
415     ##
416     # Returns the service object with the highest version number.
417     #
418     # @note <em>Warning</em>: This method should be used with great care.
419     # As APIs are updated, minor differences between versions may cause
420     # incompatibilities. Requesting a specific version will avoid this issue.
421     #
422     # @param [String, Symbol] api The name of the service.
423     #
424     # @return [Google::APIClient::API] The service object.
425     def preferred_version(api)
426       if !api.kind_of?(String) && !api.kind_of?(Symbol)
427         raise TypeError,
428           "Expected String or Symbol, got #{api.class}."
429       end
430       api = api.to_s
431       return self.discovered_apis.detect do |a|
432         a.name == api && a.preferred == true
433       end
434     end
435
436     ##
437     # Verifies an ID token against a server certificate. Used to ensure that
438     # an ID token supplied by an untrusted client-side mechanism is valid.
439     # Raises an error if the token is invalid or missing.
440     # 
441     # @deprecated Use the google-id-token gem for verifying JWTs
442     def verify_id_token!
443       require 'jwt'
444       require 'openssl'
445       @certificates ||= {}
446       if !self.authorization.respond_to?(:id_token)
447         raise ArgumentError, (
448           "Current authorization mechanism does not support ID tokens: " +
449           "#{self.authorization.class.to_s}"
450         )
451       elsif !self.authorization.id_token
452         raise ArgumentError, (
453           "Could not verify ID token, ID token missing. " +
454           "Scopes were: #{self.authorization.scope.inspect}"
455         )
456       else
457         check_cached_certs = lambda do
458           valid = false
459           for key, cert in @certificates
460             begin
461               self.authorization.decoded_id_token(cert.public_key)
462               valid = true
463             rescue JWT::DecodeError, Signet::UnsafeOperationError
464               # Expected exception. Ignore, ID token has not been validated.
465             end
466           end
467           valid
468         end
469         if check_cached_certs.call()
470           return true
471         end
472         response = self.execute!(
473           :http_method => :get,
474           :uri => 'https://www.googleapis.com/oauth2/v1/certs',
475           :authenticated => false
476         )
477         @certificates.merge!(
478           Hash[MultiJson.load(response.body).map do |key, cert|
479             [key, OpenSSL::X509::Certificate.new(cert)]
480           end]
481         )
482         if check_cached_certs.call()
483           return true
484         else
485           raise InvalidIDTokenError,
486             "Could not verify ID token against any available certificate."
487         end
488       end
489       return nil
490     end
491
492     ##
493     # Generates a request.
494     #
495     # @option options [Google::APIClient::Method] :api_method
496     #   The method object or the RPC name of the method being executed.
497     # @option options [Hash, Array] :parameters
498     #   The parameters to send to the method.
499     # @option options [Hash, Array] :headers The HTTP headers for the request.
500     # @option options [String] :body The body of the request.
501     # @option options [String] :version ("v1")
502     #   The service version. Only used if `api_method` is a `String`.
503     # @option options [#generate_authenticated_request] :authorization
504     #   The authorization mechanism for the response. Used only if
505     #   `:authenticated` is `true`.
506     # @option options [TrueClass, FalseClass] :authenticated (true)
507     #   `true` if the request must be signed or somehow
508     #   authenticated, `false` otherwise.
509     #
510     # @return [Google::APIClient::Reference] The generated request.
511     #
512     # @example
513     #   request = client.generate_request(
514     #     :api_method => 'plus.activities.list',
515     #     :parameters =>
516     #       {'collection' => 'public', 'userId' => 'me'}
517     #   )
518     def generate_request(options={})
519       options = {
520         :api_client => self
521       }.merge(options)
522       return Google::APIClient::Request.new(options)
523     end
524
525     ##
526     # Executes a request, wrapping it in a Result object.
527     #
528     # @param [Google::APIClient::Request, Hash, Array] params
529     #   Either a Google::APIClient::Request, a Hash, or an Array.
530     #
531     #   If a Google::APIClient::Request, no other parameters are expected.
532     #
533     #   If a Hash, the below parameters are handled. If an Array, the
534     #   parameters are assumed to be in the below order:
535     #
536     #   - (Google::APIClient::Method) api_method:
537     #     The method object or the RPC name of the method being executed.
538     #   - (Hash, Array) parameters:
539     #     The parameters to send to the method.
540     #   - (String) body: The body of the request.
541     #   - (Hash, Array) headers: The HTTP headers for the request.
542     #   - (Hash) options: A set of options for the request, of which:
543     #     - (#generate_authenticated_request) :authorization (default: true) -
544     #       The authorization mechanism for the response. Used only if
545     #       `:authenticated` is `true`.
546     #     - (TrueClass, FalseClass) :authenticated (default: true) -
547     #       `true` if the request must be signed or somehow
548     #       authenticated, `false` otherwise.
549     #     - (TrueClass, FalseClass) :gzip (default: true) - 
550     #       `true` if gzip enabled, `false` otherwise.
551     #     - (FixNum) :retries -
552     #       # of times to retry on recoverable errors
553     #
554     # @return [Google::APIClient::Result] The result from the API, nil if batch.
555     #
556     # @example
557     #   result = client.execute(batch_request)
558     #
559     # @example
560     #   plus = client.discovered_api('plus')
561     #   result = client.execute(
562     #     :api_method => plus.activities.list,
563     #     :parameters => {'collection' => 'public', 'userId' => 'me'}
564     #   )
565     #
566     # @see Google::APIClient#generate_request
567     def execute!(*params)
568       if params.first.kind_of?(Google::APIClient::Request)
569         request = params.shift
570         options = params.shift || {}
571       else
572         # This block of code allows us to accept multiple parameter passing
573         # styles, and maintaining some backwards compatibility.
574         #
575         # Note: I'm extremely tempted to deprecate this style of execute call.
576         if params.last.respond_to?(:to_hash) && params.size == 1
577           options = params.pop
578         else
579           options = {}
580         end
581
582         options[:api_method] = params.shift if params.size > 0
583         options[:parameters] = params.shift if params.size > 0
584         options[:body] = params.shift if params.size > 0
585         options[:headers] = params.shift if params.size > 0
586         options.update(params.shift) if params.size > 0
587         request = self.generate_request(options)
588       end
589       
590       request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
591       request.headers['Accept-Encoding'] ||= 'gzip' unless options[:gzip] == false
592       request.headers['Content-Type'] ||= ''
593       request.parameters['key'] ||= self.key unless self.key.nil?
594       request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
595
596       connection = options[:connection] || self.connection
597       request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
598       
599       tries = 1 + (options[:retries] || self.retries)
600
601       Retriable.retriable :tries => tries, 
602                           :on => [TransmissionError],
603                           :on_retry => client_error_handler(request.authorization),
604                           :interval => lambda {|attempts| (2 ** attempts) + rand} do
605         result = request.send(connection, true)
606
607         case result.status
608           when 200...300
609             result
610           when 301, 302, 303, 307
611             request = generate_request(request.to_hash.merge({
612               :uri => result.headers['location'],
613               :api_method => nil
614             }))
615             raise RedirectError.new(result.headers['location'], result)
616           when 400...500
617             raise ClientError.new(result.error_message || "A client error has occurred", result)
618           when 500...600
619             raise ServerError.new(result.error_message || "A server error has occurred", result)
620           else
621             raise TransmissionError.new(result.error_message || "A transmission error has occurred", result)
622         end
623       end
624     end
625
626     ##
627     # Same as Google::APIClient#execute!, but does not raise an exception for
628     # normal API errros.
629     #
630     # @see Google::APIClient#execute
631     def execute(*params)
632       begin
633         return self.execute!(*params)
634       rescue TransmissionError => e
635         return e.result
636       end
637     end
638
639     protected
640
641     ##
642     # Resolves a URI template against the client's configured base.
643     #
644     # @api private
645     # @param [String, Addressable::URI, Addressable::Template] template
646     #   The template to resolve.
647     # @param [Hash] mapping The mapping that corresponds to the template.
648     # @return [Addressable::URI] The expanded URI.
649     def resolve_uri(template, mapping={})
650       @base_uri ||= Addressable::URI.new(
651         :scheme => 'https',
652         :host => self.host,
653         :port => self.port
654       ).normalize
655       template = if template.kind_of?(Addressable::Template)
656         template.pattern
657       elsif template.respond_to?(:to_str)
658         template.to_str
659       else
660         raise TypeError,
661           "Expected String, Addressable::URI, or Addressable::Template, " +
662           "got #{template.class}."
663       end
664       return Addressable::Template.new(@base_uri + template).expand(mapping)
665     end
666     
667
668     ##
669     # Returns on proc for special processing of retries as not all client errors
670     # are recoverable. Only 401s should be retried and only if the credentials
671     # are refreshable
672     #
673     # @param [#fetch_access_token!] authorization
674     #   OAuth 2 credentials
675     # @return [Proc] 
676     def client_error_handler(authorization)  
677       can_refresh = authorization.respond_to?(:refresh_token) && auto_refresh_token 
678       Proc.new do |exception, tries|
679         next unless exception.kind_of?(ClientError)
680         if exception.result.status == 401 && can_refresh && tries == 1
681           begin
682             logger.debug("Attempting refresh of access token & retry of request")
683             authorization.fetch_access_token!
684             next
685           rescue Signet::AuthorizationError
686           end
687         end
688         raise exception
689       end
690     end
691
692   end
693
694 end
695
696 require 'google/api_client/version'