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