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