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