dnclabs-auth-hmac 1.1.1.2010061601

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,3 @@
1
+ pkg
2
+ *.gemspec
3
+ *.gem
data/History.txt ADDED
@@ -0,0 +1,21 @@
1
+ == 1.1.1.2010061601 2010-06-16 (dnclabs)
2
+
3
+ * Gutted Rails monkey-patching
4
+ * Added Rack support (this means it works with Rails 2.3 as Rack middleware)
5
+ * Switched out hoe for jeweler+gemcutter
6
+
7
+ == 1.1.1 2009-10-01
8
+
9
+ * Fixed bug in headers on recent versions of Ruby.
10
+
11
+ == 1.1.0 2009-02-26
12
+
13
+ * Added support for custom request signatures and service ids. (ascarter)
14
+
15
+ == 1.0.1 2008-08-22
16
+
17
+ * Fixed nil pointer exception when with_auth called with nil creds.
18
+
19
+ == 1.0.0 2008-08-11
20
+
21
+ * Initial release
data/License.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 The Kaphan Foundation
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Manifest.txt ADDED
@@ -0,0 +1,20 @@
1
+ History.txt
2
+ License.txt
3
+ Manifest.txt
4
+ PostInstall.txt
5
+ README.txt
6
+ Rakefile
7
+ config/requirements.rb
8
+ lib/auth-hmac.rb
9
+ lib/auth-hmac/version.rb
10
+ script/console
11
+ script/destroy
12
+ script/generate
13
+ setup.rb
14
+ spec/auth-hmac_spec.rb
15
+ spec/spec.opts
16
+ spec/spec_helper.rb
17
+ tasks/jeweler.rake
18
+ tasks/environment.rake
19
+ tasks/rspec.rake
20
+ tasks/website.rake
data/PostInstall.txt ADDED
@@ -0,0 +1,7 @@
1
+
2
+ For more information on auth-hmac, see http://auth-hmac.rubyforge.org
3
+
4
+ NOTE: Change this information in PostInstall.txt
5
+ You can also delete it if you don't want it.
6
+
7
+
data/README.rdoc ADDED
@@ -0,0 +1,129 @@
1
+ = auth-hmac
2
+
3
+ == What is it?
4
+
5
+ auth-hmac is a Ruby implementation of HMAC[http://en.wikipedia.org/wiki/HMAC] based authentication of HTTP requests.
6
+
7
+ HMAC authentication involves a client and server having a shared secret key. When sending the request the client, signs the request using the secret key. This involves building a canonical representation of the request and then generating a HMAC of the request using the secret. The generated HMAC is then sent as part of the request.
8
+
9
+ When the server receives the request it builds the same canonical representation and generates a HMAC using it's copy of the secret key, if the HMAC produced by the server matches the HMAC sent by the client, the server can be assured that the client also possesses the shared secret key.
10
+
11
+ HMAC based authentication also provides message integrity checking because the HMAC is based on a combination of the shared secret and the content of the request. So if any part of the request that is used to build the canonical representation is modified by a malicious party or in transit the authentication will then fail.
12
+
13
+ AuthHMAC was built to support authentication between various applications build by Peerworks[http://peerworks.org].
14
+
15
+ AuthHMAC is loosely based on the Amazon Web Services authentication scheme but without the Amazon specific components, i.e. it is HMAC for the rest of us.
16
+
17
+ == What does it require?
18
+
19
+ AuthHMAC requires Ruby's OpenSSL support. This should be standard in most Ruby builds.
20
+
21
+ == When to use it?
22
+
23
+ HMAC Authentication is best used as authentication for communication between applications such as web services. It provides better security than HTTP Basic authentication without the need to set up SSL. Of course if you need to protect the confidentiality of the data then you need SSL, but if you just want to authenticate requests without sending credentials in the clear AuthHMAC is a good choice.
24
+
25
+ == How to use it?
26
+
27
+ The simplest way to use AuthHMAC is with the AuthHMAC.sign! and AuthHMAC#authenticate? methods.
28
+
29
+ AuthHMAC.sign! takes a HTTP request object, an access id and a secret key and signs the request with the access_id and secret key.
30
+
31
+ * The HTTP request object can be a Net::HTTP::HTTPRequest object, a CGI::Request object or a Webrick HTTP request object. AuthHMAC will do its best to figure out which type it is an handle it accordingly.
32
+ * The access_id is used to identify the secret key that was used to sign the request. Think of it as like a user name, it allows you to hand out different keys to different clients and authenticate each of them individually. The access_id is sent in the clear so you should avoid making it an important string.
33
+ * The secret key is the shared secret between the client and the server. You should make this sufficiently random so that is can't be guessed or exposed to dictionary attacks. The follow code will give you a pretty good secret key:
34
+
35
+ random = File.read('/dev/random', 512)
36
+ secret_key = Base64.encode64(Digest::SHA2.new(512).digest(random))
37
+
38
+ On the server side you can then authenticate these requests using the AuthHMAC.authenticated? method. This takes the same arguments as the sign! method but returns true if the request has been signed with the access id and secret or false if it hasn't.
39
+
40
+ If you have more than one set of credentials you might find it useful to create an instance of the AuthHMAC class, passing your credentials as a Hash of access id => secret keys, like so:
41
+
42
+ @authhmac = AuthHMAC.new('access_id1' => 'secret1', 'access_id2' => 'secret2')
43
+
44
+ You can then use the instance methods of the @authhmac object to sign and authenticate requests, for example:
45
+
46
+ @authhmac.sign!(request, "access_id1")
47
+
48
+ will sign +request+ with "access_id1" and it's corresponding secret key. Similarly authentication is done like so:
49
+
50
+ @authhmac.authenticated?(request)
51
+
52
+ which will return true if the request has been signed with one of the access id and secret key pairs provided in the constructor.
53
+
54
+ === Rails Integration
55
+
56
+ AuthHMAC supports authentication within Rails controllers and signing of requests generated by Active Resource. See AuthHMAC::Rails::ControllerFilter::ClassMethods and AuthHMAC::Rails::ActiveResourceExtension::BaseHmac::ClassMethods for details.
57
+
58
+ == How does it work?
59
+
60
+ When creating a signature for a HTTP request AuthHMAC first generates a canonical representation of the request.
61
+
62
+ This canonical string is created like so:
63
+
64
+ canonical_string = HTTP-Verb + "\n" +
65
+ Content-Type + "\n" +
66
+ Content-MD5 + "\n" +
67
+ Date + "\n" +
68
+ request-uri;
69
+
70
+ Where Content-Type, Content-MD5 and Date are all taken from the headers of the request. If Content-Type or Content-MD5 are not present, they are substituted with an empty string. If Date is not present it is added to the request headers with the value +Time.now.httpdate+. +request-uri+ is the path component of the request, without any query string, i.e. everything up to the ?.
71
+
72
+ This string is then used with the secret to generate a SHA1 HMAC using the following:
73
+
74
+ OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), secret_key, canonical_string)
75
+
76
+ The result is then Base64 encoded and added to the headers of the request as the +Authorization+ header in the format:
77
+
78
+ Authorization: AuthHMAC <access_id>:<base64 encoded hmac>
79
+
80
+ When authenaticating a request, AuthHMAC looks for the Authorization header in the above format, parses out the components, regenerates a HMAC for the request, using the secret key identified by the access id and then compares the generated HMAC with the one provided by the client. If they match the request is authenticated.
81
+
82
+ Using these details it is possible to build code that will sign and authenticate AuthHMAC style requests in other languages.
83
+
84
+ == INSTALL:
85
+
86
+ * sudo gem install auth-hmac
87
+
88
+ == Source Code
89
+
90
+ The source repository is accessible via GitHub or Ruby Forge:
91
+
92
+ git clone git://github.com/seangeo/auth-hmac.git
93
+
94
+
95
+ git clone git://rubyforge.org/auth-hmac.git
96
+
97
+ == Contact Information
98
+
99
+ The project page is at http://rubyforge.org/projects/auth-hmac. Please file any bugs or feedback
100
+ using the trackers and forums there.
101
+
102
+ == Authors and Contributors
103
+
104
+ rAtom was developed by Peerworks[http://peerworks.org] and written by Sean Geoghegan.
105
+
106
+ == LICENSE:
107
+
108
+ (The MIT License)
109
+
110
+ Copyright (c) 2008 The Kaphan Foundation
111
+
112
+ Permission is hereby granted, free of charge, to any person obtaining
113
+ a copy of this software and associated documentation files (the
114
+ 'Software'), to deal in the Software without restriction, including
115
+ without limitation the rights to use, copy, modify, merge, publish,
116
+ distribute, sublicense, and/or sell copies of the Software, and to
117
+ permit persons to whom the Software is furnished to do so, subject to
118
+ the following conditions:
119
+
120
+ The above copyright notice and this permission notice shall be
121
+ included in all copies or substantial portions of the Software.
122
+
123
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
124
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
125
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
126
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
127
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
128
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
129
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.txt ADDED
@@ -0,0 +1,129 @@
1
+ = auth-hmac
2
+
3
+ == What is it?
4
+
5
+ auth-hmac is a Ruby implementation of HMAC[http://en.wikipedia.org/wiki/HMAC] based authentication of HTTP requests.
6
+
7
+ HMAC authentication involves a client and server having a shared secret key. When sending the request the client, signs the request using the secret key. This involves building a canonical representation of the request and then generating a HMAC of the request using the secret. The generated HMAC is then sent as part of the request.
8
+
9
+ When the server receives the request it builds the same canonical representation and generates a HMAC using it's copy of the secret key, if the HMAC produced by the server matches the HMAC sent by the client, the server can be assured that the client also possesses the shared secret key.
10
+
11
+ HMAC based authentication also provides message integrity checking because the HMAC is based on a combination of the shared secret and the content of the request. So if any part of the request that is used to build the canonical representation is modified by a malicious party or in transit the authentication will then fail.
12
+
13
+ AuthHMAC was built to support authentication between various applications build by Peerworks[http://peerworks.org].
14
+
15
+ AuthHMAC is loosely based on the Amazon Web Services authentication scheme but without the Amazon specific components, i.e. it is HMAC for the rest of us.
16
+
17
+ == What does it require?
18
+
19
+ AuthHMAC requires Ruby's OpenSSL support. This should be standard in most Ruby builds.
20
+
21
+ == When to use it?
22
+
23
+ HMAC Authentication is best used as authentication for communication between applications such as web services. It provides better security than HTTP Basic authentication without the need to set up SSL. Of course if you need to protect the confidentiality of the data then you need SSL, but if you just want to authenticate requests without sending credentials in the clear AuthHMAC is a good choice.
24
+
25
+ == How to use it?
26
+
27
+ The simplest way to use AuthHMAC is with the AuthHMAC.sign! and AuthHMAC#authenticate? methods.
28
+
29
+ AuthHMAC.sign! takes a HTTP request object, an access id and a secret key and signs the request with the access_id and secret key.
30
+
31
+ * The HTTP request object can be a Net::HTTP::HTTPRequest object, a CGI::Request object or a Webrick HTTP request object. AuthHMAC will do its best to figure out which type it is an handle it accordingly.
32
+ * The access_id is used to identify the secret key that was used to sign the request. Think of it as like a user name, it allows you to hand out different keys to different clients and authenticate each of them individually. The access_id is sent in the clear so you should avoid making it an important string.
33
+ * The secret key is the shared secret between the client and the server. You should make this sufficiently random so that is can't be guessed or exposed to dictionary attacks. The follow code will give you a pretty good secret key:
34
+
35
+ random = File.read('/dev/random', 512)
36
+ secret_key = Base64.encode64(Digest::SHA2.new(512).digest(random))
37
+
38
+ On the server side you can then authenticate these requests using the AuthHMAC.authenticated? method. This takes the same arguments as the sign! method but returns true if the request has been signed with the access id and secret or false if it hasn't.
39
+
40
+ If you have more than one set of credentials you might find it useful to create an instance of the AuthHMAC class, passing your credentials as a Hash of access id => secret keys, like so:
41
+
42
+ @authhmac = AuthHMAC.new('access_id1' => 'secret1', 'access_id2' => 'secret2')
43
+
44
+ You can then use the instance methods of the @authhmac object to sign and authenticate requests, for example:
45
+
46
+ @authhmac.sign!(request, "access_id1")
47
+
48
+ will sign +request+ with "access_id1" and it's corresponding secret key. Similarly authentication is done like so:
49
+
50
+ @authhmac.authenticated?(request)
51
+
52
+ which will return true if the request has been signed with one of the access id and secret key pairs provided in the constructor.
53
+
54
+ === Rails Integration
55
+
56
+ AuthHMAC supports authentication within Rails controllers and signing of requests generated by Active Resource. See AuthHMAC::Rails::ControllerFilter::ClassMethods and AuthHMAC::Rails::ActiveResourceExtension::BaseHmac::ClassMethods for details.
57
+
58
+ == How does it work?
59
+
60
+ When creating a signature for a HTTP request AuthHMAC first generates a canonical representation of the request.
61
+
62
+ This canonical string is created like so:
63
+
64
+ canonical_string = HTTP-Verb + "\n" +
65
+ Content-Type + "\n" +
66
+ Content-MD5 + "\n" +
67
+ Date + "\n" +
68
+ request-uri;
69
+
70
+ Where Content-Type, Content-MD5 and Date are all taken from the headers of the request. If Content-Type or Content-MD5 are not present, they are substituted with an empty string. If Date is not present it is added to the request headers with the value +Time.now.httpdate+. +request-uri+ is the path component of the request, without any query string, i.e. everything up to the ?.
71
+
72
+ This string is then used with the secret to generate a SHA1 HMAC using the following:
73
+
74
+ OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), secret_key, canonical_string)
75
+
76
+ The result is then Base64 encoded and added to the headers of the request as the +Authorization+ header in the format:
77
+
78
+ Authorization: AuthHMAC <access_id>:<base64 encoded hmac>
79
+
80
+ When authenaticating a request, AuthHMAC looks for the Authorization header in the above format, parses out the components, regenerates a HMAC for the request, using the secret key identified by the access id and then compares the generated HMAC with the one provided by the client. If they match the request is authenticated.
81
+
82
+ Using these details it is possible to build code that will sign and authenticate AuthHMAC style requests in other languages.
83
+
84
+ == INSTALL:
85
+
86
+ * sudo gem install auth-hmac
87
+
88
+ == Source Code
89
+
90
+ The source repository is accessible via GitHub or Ruby Forge:
91
+
92
+ git clone git://github.com/seangeo/auth-hmac.git
93
+
94
+
95
+ git clone git://rubyforge.org/auth-hmac.git
96
+
97
+ == Contact Information
98
+
99
+ The project page is at http://rubyforge.org/projects/auth-hmac. Please file any bugs or feedback
100
+ using the trackers and forums there.
101
+
102
+ == Authors and Contributors
103
+
104
+ rAtom was developed by Peerworks[http://peerworks.org] and written by Sean Geoghegan.
105
+
106
+ == LICENSE:
107
+
108
+ (The MIT License)
109
+
110
+ Copyright (c) 2008 The Kaphan Foundation
111
+
112
+ Permission is hereby granted, free of charge, to any person obtaining
113
+ a copy of this software and associated documentation files (the
114
+ 'Software'), to deal in the Software without restriction, including
115
+ without limitation the rights to use, copy, modify, merge, publish,
116
+ distribute, sublicense, and/or sell copies of the Software, and to
117
+ permit persons to whom the Software is furnished to do so, subject to
118
+ the following conditions:
119
+
120
+ The above copyright notice and this permission notice shall be
121
+ included in all copies or substantial portions of the Software.
122
+
123
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
124
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
125
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
126
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
127
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
128
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
129
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,3 @@
1
+ require 'config/requirements'
2
+
3
+ Dir['tasks/**/*.rake'].each { |rake| load rake }
data/bin/auth-hmac ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env ruby
2
+ APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
3
+
4
+ require 'openssl'
5
+ require 'base64'
6
+
7
+ def usage
8
+ puts "Usage: auth-hmac COMMAND [ARGS]"
9
+ puts "\nCommands:"
10
+ puts " signature [secret] [signature string] Creates HMAC digtest using optional secret"
11
+ exit
12
+ end
13
+
14
+ def signature(args)
15
+ secret = args[0]
16
+ signature = args[1]
17
+ digest = OpenSSL::Digest::Digest.new('sha1')
18
+ puts Base64.encode64(OpenSSL::HMAC.digest(digest, secret, signature)).strip
19
+ end
20
+
21
+ #
22
+ # MAIN
23
+ #
24
+
25
+ usage if ['--help', '-h'].include?(ARGV[0])
26
+
27
+ command = ARGV.shift
28
+ args = []
29
+ ARGV.each { |arg| args << arg }
30
+
31
+ usage if command.nil?
32
+
33
+ case command
34
+ when "signature"
35
+ signature(args)
36
+ end
37
+
38
+
@@ -0,0 +1,15 @@
1
+ require 'fileutils'
2
+ include FileUtils
3
+
4
+ require 'rubygems'
5
+ %w[rake jeweler].each do |req_gem|
6
+ begin
7
+ require req_gem
8
+ rescue LoadError
9
+ puts "This Rakefile requires the '#{req_gem}' RubyGem."
10
+ puts "Installation: gem install #{req_gem} -y"
11
+ exit
12
+ end
13
+ end
14
+
15
+ $:.unshift(File.join(File.dirname(__FILE__), %w[.. lib]))
@@ -0,0 +1,10 @@
1
+ class AuthHMAC
2
+ module VERSION #:nodoc:
3
+ MAJOR = 1
4
+ MINOR = 1
5
+ TINY = 1
6
+ LOCAL = 2010061601
7
+
8
+ STRING = [MAJOR, MINOR, TINY, LOCAL].join('.')
9
+ end
10
+ end
data/lib/auth-hmac.rb ADDED
@@ -0,0 +1,252 @@
1
+ # Copyright (c) 2008 The Kaphan Foundation
2
+ #
3
+ # See License.txt for licensing information.
4
+ #
5
+
6
+ $:.unshift(File.dirname(__FILE__)) unless
7
+ $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
8
+
9
+ require 'openssl'
10
+ require 'base64'
11
+
12
+ # This module provides a HMAC Authentication method for HTTP requests. It should work with
13
+ # net/http request classes and CGIRequest classes and hence Rails.
14
+ #
15
+ # It is loosely based on the Amazon Web Services Authentication mechanism but
16
+ # generalized to be useful to any application that requires HMAC based authentication.
17
+ # As a result of the generalization, it won't work with AWS because it doesn't support
18
+ # the Amazon extension headers.
19
+ #
20
+ # === References
21
+ # Cryptographic Hash functions:: http://en.wikipedia.org/wiki/Cryptographic_hash_function
22
+ # SHA-1 Hash function:: http://en.wikipedia.org/wiki/SHA-1
23
+ # HMAC algorithm:: http://en.wikipedia.org/wiki/HMAC
24
+ # RFC 2104:: http://tools.ietf.org/html/rfc2104
25
+ #
26
+ class AuthHMAC
27
+ module Headers # :nodoc:
28
+ # Gets the headers for a request.
29
+ #
30
+ # Attempts to deal with known HTTP header representations in Ruby.
31
+ # Currently handles net/http and Rails.
32
+ #
33
+ def headers(request)
34
+ if request.respond_to?(:headers)
35
+ request.headers
36
+ elsif request.respond_to?(:env)
37
+ request.env.each_pair do |key,value|
38
+ if value.is_a?(Array) && value.size == 1
39
+ request.env[key] = value[0]
40
+ end
41
+ end
42
+ request.env
43
+ elsif request.respond_to?(:[])
44
+ request
45
+ else
46
+ raise ArgumentError, "Don't know how to get the headers from #{request.inspect}"
47
+ end
48
+ end
49
+
50
+ def find_header(keys, headers)
51
+ keys.map do |key|
52
+ headers[key]
53
+ end.compact.first
54
+ end
55
+ end
56
+
57
+ include Headers
58
+
59
+ # Build a Canonical String for a HTTP request.
60
+ #
61
+ # A Canonical String has the following format:
62
+ #
63
+ # CanonicalString = HTTP-Verb + "\n" +
64
+ # Content-Type + "\n" +
65
+ # Content-MD5 + "\n" +
66
+ # Date + "\n" +
67
+ # request-uri;
68
+ #
69
+ #
70
+ # If the Date header doesn't exist, one will be generated since
71
+ # Net/HTTP will generate one if it doesn't exist and it will be
72
+ # used on the server side to do authentication.
73
+ #
74
+ class CanonicalString < String # :nodoc:
75
+ include Headers
76
+
77
+ def initialize(request)
78
+ self << request_method(request) + "\n"
79
+ self << header_values(headers(request)) + "\n"
80
+ self << request_path(request)
81
+ end
82
+
83
+ private
84
+ def request_method(request)
85
+ if request.respond_to?(:request_method) && request.request_method.is_a?(String)
86
+ request.request_method
87
+ elsif request.respond_to?(:method) && request.method.is_a?(String)
88
+ request.method
89
+ elsif request.respond_to?(:env) && request.env
90
+ request.env['REQUEST_METHOD']
91
+ else
92
+ raise ArgumentError, "Don't know how to get the request method from #{request.inspect}"
93
+ end
94
+ end
95
+
96
+ def header_values(headers)
97
+ [ content_type(headers),
98
+ content_md5(headers),
99
+ (date(headers) or headers['Date'] = Time.now.utc.httpdate)
100
+ ].join("\n")
101
+ end
102
+
103
+ def content_type(headers)
104
+ find_header(%w(CONTENT-TYPE CONTENT_TYPE HTTP_CONTENT_TYPE), headers)
105
+ end
106
+
107
+ def date(headers)
108
+ find_header(%w(DATE HTTP_DATE), headers)
109
+ end
110
+
111
+ def content_md5(headers)
112
+ find_header(%w(CONTENT-MD5 CONTENT_MD5), headers)
113
+ end
114
+
115
+ def request_path(request)
116
+ # Try unparsed_uri in case it is a Webrick request
117
+ path = if request.respond_to?(:unparsed_uri)
118
+ request.unparsed_uri
119
+ else
120
+ request.path
121
+ end
122
+
123
+ path[/^[^?]*/]
124
+ end
125
+ end
126
+
127
+ @@default_signature_class = CanonicalString
128
+
129
+ # Create an AuthHMAC instance using the given credential store
130
+ #
131
+ # Credential Store:
132
+ # * Credential store must respond to the [] method and return a secret for access key id
133
+ #
134
+ # Options:
135
+ # Override default options
136
+ # * <tt>:service_id</tt> - Service ID used in the AUTHORIZATION header string. Default is AuthHMAC.
137
+ # * <tt>:signature_method</tt> - Proc object that takes request and produces the signature string
138
+ # used for authentication. Default is CanonicalString.
139
+ # Examples:
140
+ # my_hmac = AuthHMAC.new('access_id1' => 'secret1', 'access_id2' => 'secret2')
141
+ #
142
+ # cred_store = { 'access_id1' => 'secret1', 'access_id2' => 'secret2' }
143
+ # options = { :service_id => 'MyApp', :signature_method => lambda { |r| MyRequestString.new(r) } }
144
+ # my_hmac = AuthHMAC.new(cred_store, options)
145
+ #
146
+ def initialize(credential_store, options = nil)
147
+ @credential_store = credential_store
148
+
149
+ # Defaults
150
+ @service_id = self.class.name
151
+ @signature_class = @@default_signature_class
152
+
153
+ unless options.nil?
154
+ @service_id = options[:service_id] if options.key?(:service_id)
155
+ @signature_class = options[:signature] if options.key?(:signature) && options[:signature].is_a?(Class)
156
+ end
157
+
158
+ @signature_method = lambda { |r| @signature_class.send(:new, r) }
159
+ end
160
+
161
+ # Generates canonical signing string for given request
162
+ #
163
+ # Supports same options as AuthHMAC.initialize for overriding service_id and
164
+ # signature method.
165
+ #
166
+ def AuthHMAC.canonical_string(request, options = nil)
167
+ self.new(nil, options).canonical_string(request)
168
+ end
169
+
170
+ # Generates signature string for a given secret
171
+ #
172
+ # Supports same options as AuthHMAC.initialize for overriding service_id and
173
+ # signature method.
174
+ #
175
+ def AuthHMAC.signature(request, secret, options = nil)
176
+ self.new(nil, options).signature(request, secret)
177
+ end
178
+
179
+ # Signs a request using a given access key id and secret.
180
+ #
181
+ # Supports same options as AuthHMAC.initialize for overriding service_id and
182
+ # signature method.
183
+ #
184
+ def AuthHMAC.sign!(request, access_key_id, secret, options = nil)
185
+ credentials = { access_key_id => secret }
186
+ self.new(credentials, options).sign!(request, access_key_id)
187
+ end
188
+
189
+ # Authenticates a request using HMAC
190
+ #
191
+ # Supports same options as AuthHMAC.initialize for overriding service_id and
192
+ # signature method.
193
+ #
194
+ def AuthHMAC.authenticated?(request, access_key_id, secret, options)
195
+ credentials = { access_key_id => secret }
196
+ self.new(credentials, options).authenticated?(request)
197
+ end
198
+
199
+ # Signs a request using the access_key_id and the secret associated with that id
200
+ # in the credential store.
201
+ #
202
+ # Signing a requests adds an Authorization header to the request in the format:
203
+ #
204
+ # <service_id> <access_key_id>:<signature>
205
+ #
206
+ # where <signature> is the Base64 encoded HMAC-SHA1 of the CanonicalString and the secret.
207
+ #
208
+ def sign!(request, access_key_id)
209
+ secret = @credential_store[access_key_id]
210
+ raise ArgumentError, "No secret found for key id '#{access_key_id}'" if secret.nil?
211
+ if request.respond_to?(:headers)
212
+ request.headers['Authorization'] = authorization(request, access_key_id, secret)
213
+ else
214
+ request['Authorization'] = authorization(request, access_key_id, secret)
215
+ end
216
+ end
217
+
218
+ # Authenticates a request using HMAC
219
+ #
220
+ # Returns true if the request has an AuthHMAC Authorization header and
221
+ # the access id and HMAC match an id and HMAC produced for the secret
222
+ # in the credential store. Otherwise returns false.
223
+ #
224
+ def authenticated?(request)
225
+ rx = Regexp.new("#{@service_id} ([^:]+):(.+)$")
226
+ if md = rx.match(authorization_header(request))
227
+ access_key_id = md[1]
228
+ hmac = md[2]
229
+ secret = @credential_store[access_key_id]
230
+ !secret.nil? && hmac == signature(request, secret)
231
+ else
232
+ false
233
+ end
234
+ end
235
+
236
+ def signature(request, secret)
237
+ digest = OpenSSL::Digest::Digest.new('sha1')
238
+ Base64.encode64(OpenSSL::HMAC.digest(digest, secret, canonical_string(request))).strip
239
+ end
240
+
241
+ def canonical_string(request)
242
+ @signature_method.call(request)
243
+ end
244
+
245
+ def authorization_header(request)
246
+ find_header(%w(Authorization HTTP_AUTHORIZATION), headers(request))
247
+ end
248
+
249
+ def authorization(request, access_key_id, secret)
250
+ "#{@service_id} #{access_key_id}:#{signature(request, secret)}"
251
+ end
252
+ end
data/script/console ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env ruby
2
+ # File: script/console
3
+ irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
4
+
5
+ libs = " -r irb/completion"
6
+ # Perhaps use a console_lib to store any extra methods I may want available in the cosole
7
+ # libs << " -r #{File.dirname(__FILE__) + '/../lib/console_lib/console_logger.rb'}"
8
+ libs << " -r #{File.dirname(__FILE__) + '/../lib/auth-hmac.rb'}"
9
+ puts "Loading auth-hmac gem"
10
+ exec "#{irb} #{libs} --simple-prompt"