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