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