lib/api_auth/base.rb in api-auth-2.1.0 vs lib/api_auth/base.rb in api-auth-2.2.0

- old
+ new

@@ -1,6 +1,5 @@ -# encoding: UTF-8 # api-auth is a Ruby gem designed to be used both in your client and server # HTTP-based applications. It implements the same authentication methods (HMAC) # used by Amazon Web Services. # The gem will sign your requests on the client side and authenticate that @@ -19,11 +18,11 @@ # # access_id: The public unique identifier for the client # # secret_key: assigned secret key that is known to both parties def sign!(request, access_id, secret_key, options = {}) - options = { :override_http_method => nil, :digest => 'sha1' }.merge(options) + options = { override_http_method: nil, digest: 'sha1' }.merge(options) headers = Headers.new(request) headers.calculate_md5 headers.set_date headers.sign_header auth_header(headers, access_id, secret_key, options) end @@ -31,19 +30,22 @@ # Determines if the request is authentic given the request and the client's # secret key. Returns true if the request is authentic and false otherwise. def authentic?(request, secret_key, options = {}) return false if secret_key.nil? - options = { :override_http_method => nil }.merge(options) + options = { override_http_method: nil }.merge(options) headers = Headers.new(request) + # 900 seconds is 15 minutes + clock_skew = options.fetch(:clock_skew, 900) + if headers.md5_mismatch? false elsif !signatures_match?(headers, secret_key, options) false - elsif !request_within_time_window?(headers) + elsif !request_within_time_window?(headers, clock_skew) false else true end end @@ -69,15 +71,13 @@ private AUTH_HEADER_PATTERN = /APIAuth(?:-HMAC-(MD5|SHA(?:1|224|256|384|512)?))? ([^:]+):(.+)$/ - def request_within_time_window?(headers) - # 900 seconds is 15 minutes - - Time.httpdate(headers.timestamp).utc > (Time.now.utc - 900) && - Time.httpdate(headers.timestamp).utc < (Time.now.utc + 900) + def request_within_time_window?(headers, clock_skew) + Time.httpdate(headers.timestamp).utc > (Time.now.utc - clock_skew) && + Time.httpdate(headers.timestamp).utc < (Time.now.utc + clock_skew) rescue ArgumentError false end def signatures_match?(headers, secret_key, options) @@ -85,10 +85,10 @@ return false unless match_data digest = match_data[1].nil? ? 'SHA1' : match_data[1].upcase raise InvalidRequestDigest if !options[:digest].nil? && !options[:digest].casecmp(digest).zero? - options = { :digest => digest }.merge(options) + options = { digest: digest }.merge(options) header_sig = match_data[3] calculated_sig = hmac_signature(headers, secret_key, options) secure_equals?(header_sig, calculated_sig, secret_key)