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