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