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