Skip to content

Commit

Permalink
Merge pull request rack#958 from frodsan/custom-hmac
Browse files Browse the repository at this point in the history
Add support for custom hmac.
  • Loading branch information
spastorino committed Oct 11, 2015
2 parents 2f782ce + 68ea528 commit 6216a3f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/rack/session/cookie.rb
Expand Up @@ -105,6 +105,8 @@ def decode(str); str; end

def initialize(app, options={})
@secrets = options.values_at(:secret, :old_secret).compact
@hmac = options.fetch(:hmac, OpenSSL::Digest::SHA1)

warn <<-MSG unless secure?(options)
SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
This poses a security threat. It is strongly recommended that you
Expand Down Expand Up @@ -180,7 +182,7 @@ def digest_match?(data, digest)
end

def generate_hmac(data, secret)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data)
OpenSSL::HMAC.hexdigest(@hmac.new, secret, data)
end

def secure?(options)
Expand Down
16 changes: 16 additions & 0 deletions test/spec_session_cookie.rb
Expand Up @@ -311,6 +311,22 @@ def decode(str); @calls << :decode; str; end
response.body.must_equal '{"counter"=>2}'
end

it "supports custom digest class" do
app = [incrementor, { :secret => "test", hmac: OpenSSL::Digest::SHA256 }]

response = response_for(:app => app)
response = response_for(:app => app, :cookie => response)
response.body.must_equal '{"counter"=>2}'

response = response_for(:app => app, :cookie => response)
response.body.must_equal '{"counter"=>3}'

app = [incrementor, { :secret => "other" }]

response = response_for(:app => app, :cookie => response)
response.body.must_equal '{"counter"=>1}'
end

it "can handle Rack::Lint middleware" do
response = response_for(:app => incrementor)

Expand Down

0 comments on commit 6216a3f

Please sign in to comment.