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