class Shmac::SignatureCalculator

Attributes

header_namespace[R]
options[R]
request[R]
secret[R]

Public Class Methods

new(secret:, request:, header_namespace: nil, options: {}) click to toggle source
# File lib/shmac/signature_calculator.rb, line 8
def initialize secret:, request:, header_namespace: nil, options: {}
  @secret = secret
  @request = request
  @header_namespace = header_namespace.downcase if header_namespace
  @options = options
end

Public Instance Methods

canonicalized_platform_headers() click to toggle source
# File lib/shmac/signature_calculator.rb, line 42
def canonicalized_platform_headers
  return unless self.header_namespace

  normalize_key = -> (key) { key.to_s.downcase.strip }
  normalize_value = -> (value) { value.to_s.strip }
  canonicalized_header_row = -> (k,v) {
    "%s:%s" % [normalize_key.(k), normalize_value.(v)]
  }
  matches_namespace = ->(value) { value.start_with?(header_namespace) }

  self.request.headers
    .map(&canonicalized_header_row)
    .find_all(&matches_namespace)
    .sort
    .join("\n")
end
signature() click to toggle source
# File lib/shmac/signature_calculator.rb, line 19
def signature
  digest = OpenSSL::Digest.new "sha1"
  hmac = OpenSSL::HMAC.digest digest, secret, string_to_sign
  Base64.strict_encode64 hmac
end
string_to_sign() click to toggle source
# File lib/shmac/signature_calculator.rb, line 25
def string_to_sign
  parts = [
    request.method,
    request.content_md5,
    request.content_type,
    request.date(self.header_namespace)
  ]

  platform_headers = canonicalized_platform_headers.to_s.strip
  parts << platform_headers unless platform_headers.empty?

  # Some clients do not know to which endpoint a message is sent
  parts << request.path unless options[:skip_path]

  parts.join("\n")
end
to_s() click to toggle source
# File lib/shmac/signature_calculator.rb, line 15
def to_s
  signature
end