Module: EY::ApiHMAC

Defined in:
lib/ey_api_hmac.rb,
lib/ey_api_hmac/sso.rb,
lib/ey_api_hmac/version.rb,
lib/ey_api_hmac/api_auth.rb,
lib/ey_api_hmac/base_connection.rb

Defined Under Namespace

Modules: ApiAuth, SSO Classes: BaseConnection, HmacAuthFail

Constant Summary

VERSION =
"0.1.0"

Class Method Summary (collapse)

Class Method Details

+ (Object) auth_string(key_id, signature)



33
34
35
# File 'lib/ey_api_hmac.rb', line 33

def self.auth_string(key_id, signature)
  "AuthHMAC #{key_id}:#{signature}"
end

+ (Object) authenticate!(env, &lookup)



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ey_api_hmac.rb', line 48

def self.authenticate!(env, &lookup)
  rx = Regexp.new("AuthHMAC ([^:]+):(.+)$")
  if md = rx.match(env["HTTP_AUTHORIZATION"])
    access_key_id = md[1]
    hmac = md[2]
    secret = lookup.call(access_key_id)
    unless secret
      raise HmacAuthFail, "couldn't find auth for #{access_key_id}"
    end
    unless hmac == signature(env, secret)
      raise HmacAuthFail, "signature mismatch. Calculated canonical_string: #{canonical_string(env).inspect}"
    end
  else
    raise HmacAuthFail, "no authorization header"
  end
end

+ (Boolean) authenticated?(env, &lookup)

Returns:

  • (Boolean)


65
66
67
68
69
70
71
72
# File 'lib/ey_api_hmac.rb', line 65

def self.authenticated?(env, &lookup)
  begin
    authenticate!(env, &lookup)
    true
  rescue HmacAuthFail => e
    false
  end
end

+ (Object) base64digest(data, secret)



41
42
43
44
# File 'lib/ey_api_hmac.rb', line 41

def self.base64digest(data,secret)
  digest = OpenSSL::Digest::Digest.new('sha1')
  [OpenSSL::HMAC.digest(digest, secret, data)].pack('m').strip
end

+ (Object) canonical_string(env)



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/ey_api_hmac.rb', line 13

def self.canonical_string(env)
  parts = []
  expect = Proc.new do |var|
    unless env[var]
      raise HmacAuthFail, "'#{var}' header missing and required in #{env.inspect}"
    end
    env[var]
  end
  parts << expect["REQUEST_METHOD"]
  parts << env["CONTENT_TYPE"]
  parts << generated_md5(env)
  parts << expect["HTTP_DATE"]
  if env["REQUEST_URI"]
    parts << URI.parse(env["REQUEST_URI"]).path
  else
    parts << expect["PATH_INFO"]
  end
  parts.join("\n")
end

+ (Object) sign!(env, key_id, secret)



9
10
11
# File 'lib/ey_api_hmac.rb', line 9

def self.sign!(env, key_id, secret)
  env["HTTP_AUTHORIZATION"] = auth_string(key_id, signature(env, secret))
end

+ (Object) signature(env, secret)



37
38
39
# File 'lib/ey_api_hmac.rb', line 37

def self.signature(env, secret)
  base64digest(canonical_string(env), secret)
end