ascarter-auth-hmac 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/History.txt ADDED
@@ -0,0 +1,7 @@
1
+ == 1.0.1 2008-08-22
2
+
3
+ * Fixed nil pointer exception when with_auth called with nil creds.
4
+
5
+ == 1.0.0 2008-08-11
6
+
7
+ * 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,21 @@
1
+ History.txt
2
+ License.txt
3
+ Manifest.txt
4
+ PostInstall.txt
5
+ README.txt
6
+ Rakefile
7
+ config/hoe.rb
8
+ config/requirements.rb
9
+ lib/auth-hmac.rb
10
+ lib/auth-hmac/version.rb
11
+ script/console
12
+ script/destroy
13
+ script/generate
14
+ setup.rb
15
+ spec/auth-hmac_spec.rb
16
+ spec/spec.opts
17
+ spec/spec_helper.rb
18
+ tasks/deployment.rake
19
+ tasks/environment.rake
20
+ tasks/rspec.rake
21
+ 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.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,4 @@
1
+ require 'config/requirements'
2
+ require 'config/hoe' # setup Hoe + all gem configuration
3
+
4
+ Dir['tasks/**/*.rake'].each { |rake| load rake }
data/config/hoe.rb ADDED
@@ -0,0 +1,73 @@
1
+ require 'auth-hmac/version'
2
+
3
+ AUTHOR = 'Sean Geoghegan' # can also be an array of Authors
4
+ EMAIL = "seangeo@gmail.com"
5
+ DESCRIPTION = "A gem providing HMAC based authentication for HTTP"
6
+ GEM_NAME = 'auth-hmac' # what ppl will type to install your gem
7
+ RUBYFORGE_PROJECT = 'auth-hmac' # The unix name for your project
8
+ HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org"
9
+ DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}"
10
+ EXTRA_DEPENDENCIES = [
11
+ # ['activesupport', '>= 1.3.1']
12
+ ] # An array of rubygem dependencies [name, version]
13
+
14
+ @config_file = "~/.rubyforge/user-config.yml"
15
+ @config = nil
16
+ RUBYFORGE_USERNAME = "unknown"
17
+ def rubyforge_username
18
+ unless @config
19
+ begin
20
+ @config = YAML.load(File.read(File.expand_path(@config_file)))
21
+ rescue
22
+ puts <<-EOS
23
+ ERROR: No rubyforge config file found: #{@config_file}
24
+ Run 'rubyforge setup' to prepare your env for access to Rubyforge
25
+ - See http://newgem.rubyforge.org/rubyforge.html for more details
26
+ EOS
27
+ exit
28
+ end
29
+ end
30
+ RUBYFORGE_USERNAME.replace @config["username"]
31
+ end
32
+
33
+
34
+ REV = nil
35
+ # UNCOMMENT IF REQUIRED:
36
+ # REV = YAML.load(`svn info`)['Revision']
37
+ VERS = AuthHMAC::VERSION::STRING + (REV ? ".#{REV}" : "")
38
+ RDOC_OPTS = ['--quiet', '--title', 'auth-hmac documentation',
39
+ "--opname", "index.html",
40
+ "--line-numbers",
41
+ "--main", "README",
42
+ "--inline-source"]
43
+
44
+ class Hoe
45
+ def extra_deps
46
+ @extra_deps.reject! { |x| Array(x).first == 'hoe' }
47
+ @extra_deps
48
+ end
49
+ end
50
+
51
+ # Generate all the Rake tasks
52
+ # Run 'rake -T' to see list of generated tasks (from gem root directory)
53
+ $hoe = Hoe.new(GEM_NAME, VERS) do |p|
54
+ p.developer(AUTHOR, EMAIL)
55
+ p.description = DESCRIPTION
56
+ p.summary = DESCRIPTION
57
+ p.url = HOMEPATH
58
+ p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
59
+ p.test_globs = ["test/**/test_*.rb"]
60
+ p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean.
61
+
62
+ # == Optional
63
+ p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n")
64
+ #p.extra_deps = EXTRA_DEPENDENCIES
65
+
66
+ #p.spec_extras = {} # A hash of extra values to set in the gemspec.
67
+ end
68
+
69
+ CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n")
70
+ PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}"
71
+ $hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''))
72
+ $hoe.rsync_args = '-av --delete --ignore-errors'
73
+ $hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue ""
@@ -0,0 +1,15 @@
1
+ require 'fileutils'
2
+ include FileUtils
3
+
4
+ require 'rubygems'
5
+ %w[rake hoe newgem rubigen].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]))
data/lib/auth-hmac.rb ADDED
@@ -0,0 +1,407 @@
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?(:[])
35
+ request
36
+ elsif request.respond_to?(:headers)
37
+ request.headers
38
+ else
39
+ raise ArgumentError, "Don't know how to get the headers from #{request.inspect}"
40
+ end
41
+ end
42
+
43
+ def find_header(keys, headers)
44
+ keys.map do |key|
45
+ headers[key]
46
+ end.compact.first
47
+ end
48
+ end
49
+
50
+ include Headers
51
+
52
+ # Build a Canonical String for a HTTP request.
53
+ #
54
+ # A Canonical String has the following format:
55
+ #
56
+ # CanonicalString = HTTP-Verb + "\n" +
57
+ # Content-Type + "\n" +
58
+ # Content-MD5 + "\n" +
59
+ # Date + "\n" +
60
+ # request-uri;
61
+ #
62
+ #
63
+ # If the Date header doesn't exist, one will be generated since
64
+ # Net/HTTP will generate one if it doesn't exist and it will be
65
+ # used on the server side to do authentication.
66
+ #
67
+ class CanonicalString < String # :nodoc:
68
+ include Headers
69
+
70
+ def initialize(request)
71
+ self << request_method(request) + "\n"
72
+ self << header_values(headers(request)) + "\n"
73
+ self << request_path(request)
74
+ end
75
+
76
+ private
77
+ def request_method(request)
78
+ if request.respond_to?(:request_method) && request.request_method.is_a?(String)
79
+ request.request_method
80
+ elsif request.respond_to?(:method) && request.method.is_a?(String)
81
+ request.method
82
+ elsif request.respond_to?(:env) && request.env
83
+ request.env['REQUEST_METHOD']
84
+ else
85
+ raise ArgumentError, "Don't know how to get the request method from #{request.inspect}"
86
+ end
87
+ end
88
+
89
+ def header_values(headers)
90
+ [ content_type(headers),
91
+ content_md5(headers),
92
+ (date(headers) or headers['Date'] = Time.now.utc.httpdate)
93
+ ].join("\n")
94
+ end
95
+
96
+ def content_type(headers)
97
+ find_header(%w(CONTENT-TYPE CONTENT_TYPE HTTP_CONTENT_TYPE), headers)
98
+ end
99
+
100
+ def date(headers)
101
+ find_header(%w(DATE HTTP_DATE), headers)
102
+ end
103
+
104
+ def content_md5(headers)
105
+ find_header(%w(CONTENT-MD5 CONTENT_MD5), headers)
106
+ end
107
+
108
+ def request_path(request)
109
+ # Try unparsed_uri in case it is a Webrick request
110
+ path = if request.respond_to?(:unparsed_uri)
111
+ request.unparsed_uri
112
+ else
113
+ request.path
114
+ end
115
+
116
+ path[/^[^?]*/]
117
+ end
118
+ end
119
+
120
+ # @@default_signature_method = lambda { |r| CanonicalString.new(r) }
121
+ @@default_signature_class = CanonicalString
122
+
123
+ # Create an AuthHMAC instance using the given credential store
124
+ #
125
+ # Credential Store:
126
+ # * Credential store must respond to the [] method and return a secret for access key id
127
+ #
128
+ # Options:
129
+ # Override default options
130
+ # * <tt>:service_id</tt> - Service ID used in the AUTHORIZATION header string. Default is AuthHMAC.
131
+ # * <tt>:signature_method</tt> - Proc object that takes request and produces the signature string
132
+ # used for authentication. Default is CanonicalString.
133
+ # Examples:
134
+ # my_hmac = AuthHMAC.new('access_id1' => 'secret1', 'access_id2' => 'secret2')
135
+ #
136
+ # cred_store = { 'access_id1' => 'secret1', 'access_id2' => 'secret2' }
137
+ # options = { :service_id => 'MyApp', :signature_method => lambda { |r| MyRequestString.new(r) } }
138
+ # my_hmac = AuthHMAC.new(cred_store, options)
139
+ #
140
+ def initialize(credential_store, options = nil)
141
+ @credential_store = credential_store
142
+
143
+ # Defaults
144
+ @service_id = self.class.name
145
+ @signature_class = @@default_signature_class
146
+ #@signature_method = @@default_signature_method
147
+
148
+ unless options.nil?
149
+ @service_id = options[:service_id] if options.key?(:service_id)
150
+ @signature_class = options[:signature] if options.key?(:signature) && options[:signature].is_a?(Class)
151
+ end
152
+
153
+ @signature_method = lambda { |r| @signature_class.send(:new, r) }
154
+ end
155
+
156
+ # Generates canonical signing string for given request
157
+ #
158
+ # Supports same options as AuthHMAC.initialize for overriding service_id and
159
+ # signature method.
160
+ #
161
+ def AuthHMAC.canonical_string(request, options = nil)
162
+ self.new(nil, options).canonical_string(request)
163
+ end
164
+
165
+ # Generates signature string for a given secret
166
+ #
167
+ # Supports same options as AuthHMAC.initialize for overriding service_id and
168
+ # signature method.
169
+ #
170
+ def AuthHMAC.signature(request, secret, options = nil)
171
+ self.new(nil, options).signature(request, secret)
172
+ end
173
+
174
+ # Signs a request using a given access key id and secret.
175
+ #
176
+ # Supports same options as AuthHMAC.initialize for overriding service_id and
177
+ # signature method.
178
+ #
179
+ def AuthHMAC.sign!(request, access_key_id, secret, options = nil)
180
+ credentials = { access_key_id => secret }
181
+ self.new(credentials, options).sign!(request, access_key_id)
182
+ end
183
+
184
+ # Authenticates a request using HMAC
185
+ #
186
+ # Supports same options as AuthHMAC.initialize for overriding service_id and
187
+ # signature method.
188
+ #
189
+ def AuthHMAC.authenticated?(request, access_key_id, secret, options)
190
+ credentials = { access_key_id => secret }
191
+ self.new(credentials, options).authenticated?(request)
192
+ end
193
+
194
+ # Signs a request using the access_key_id and the secret associated with that id
195
+ # in the credential store.
196
+ #
197
+ # Signing a requests adds an Authorization header to the request in the format:
198
+ #
199
+ # <service_id> <access_key_id>:<signature>
200
+ #
201
+ # where <signature> is the Base64 encoded HMAC-SHA1 of the CanonicalString and the secret.
202
+ #
203
+ def sign!(request, access_key_id)
204
+ secret = @credential_store[access_key_id]
205
+ raise ArgumentError, "No secret found for key id '#{access_key_id}'" if secret.nil?
206
+ request['Authorization'] = authorization(request, access_key_id, secret)
207
+ end
208
+
209
+ # Authenticates a request using HMAC
210
+ #
211
+ # Returns true if the request has an AuthHMAC Authorization header and
212
+ # the access id and HMAC match an id and HMAC produced for the secret
213
+ # in the credential store. Otherwise returns false.
214
+ #
215
+ def authenticated?(request)
216
+ rx = Regexp.new("#{@service_id} ([^:]+):(.+)$")
217
+ if md = rx.match(authorization_header(request))
218
+ access_key_id = md[1]
219
+ hmac = md[2]
220
+ secret = @credential_store[access_key_id]
221
+ !secret.nil? && hmac == signature(request, secret)
222
+ else
223
+ false
224
+ end
225
+ end
226
+
227
+ def signature(request, secret)
228
+ digest = OpenSSL::Digest::Digest.new('sha1')
229
+ Base64.encode64(OpenSSL::HMAC.digest(digest, secret, canonical_string(request))).strip
230
+ end
231
+
232
+ def canonical_string(request)
233
+ @signature_method.call(request)
234
+ end
235
+
236
+ def authorization_header(request)
237
+ find_header(%w(Authorization HTTP_AUTHORIZATION), headers(request))
238
+ end
239
+
240
+ def authorization(request, access_key_id, secret)
241
+ "#{@service_id} #{access_key_id}:#{signature(request, secret)}"
242
+ end
243
+
244
+ # Integration with Rails
245
+ #
246
+ class Rails # :nodoc:
247
+ module ControllerFilter # :nodoc:
248
+ module ClassMethods
249
+ # Call within a Rails Controller to initialize HMAC authentication for the controller.
250
+ #
251
+ # * +credentials+ must be a hash that indexes secrets by their access key id.
252
+ # * +options+ supports the following arguments:
253
+ # * +failure_message+: The text to use when authentication fails.
254
+ # * +only+: A list off actions to protect.
255
+ # * +except+: A list of actions to not protect.
256
+ # * +hmac+: Options for HMAC creation. See AuthHMAC#initialize for options.
257
+ #
258
+ def with_auth_hmac(credentials, options = {})
259
+ unless credentials.nil?
260
+ self.credentials = credentials
261
+ self.authhmac_failure_message = (options.delete(:failure_message) or "HMAC Authentication failed")
262
+ self.authhmac = AuthHMAC.new(self.credentials, options.delete(:hmac))
263
+ before_filter(:hmac_login_required, options)
264
+ else
265
+ $stderr.puts("with_auth_hmac called with nil credentials - authentication will be skipped")
266
+ end
267
+ end
268
+ end
269
+
270
+ module InstanceMethods # :nodoc:
271
+ def hmac_login_required
272
+ unless hmac_authenticated?
273
+ response.headers['WWW-Authenticate'] = 'AuthHMAC'
274
+ render :text => self.class.authhmac_failure_message, :status => :unauthorized
275
+ end
276
+ end
277
+
278
+ def hmac_authenticated?
279
+ self.class.authhmac.nil? ? true : self.class.authhmac.authenticated?(request)
280
+ end
281
+ end
282
+
283
+ unless defined?(ActionController)
284
+ begin
285
+ require 'rubygems'
286
+ gem 'actionpack'
287
+ gem 'activesupport'
288
+ require 'action_controller'
289
+ require 'active_support'
290
+ rescue
291
+ nil
292
+ end
293
+ end
294
+
295
+ if defined?(ActionController::Base)
296
+ ActionController::Base.class_eval do
297
+ class_inheritable_accessor :authhmac
298
+ class_inheritable_accessor :credentials
299
+ class_inheritable_accessor :authhmac_failure_message
300
+ end
301
+
302
+ ActionController::Base.send(:include, ControllerFilter::InstanceMethods)
303
+ ActionController::Base.extend(ControllerFilter::ClassMethods)
304
+ end
305
+ end
306
+
307
+ module ActiveResourceExtension # :nodoc:
308
+ module BaseHmac # :nodoc:
309
+ def self.included(base)
310
+ base.extend(ClassMethods)
311
+
312
+ base.class_inheritable_accessor :hmac_access_id
313
+ base.class_inheritable_accessor :hmac_secret
314
+ base.class_inheritable_accessor :use_hmac
315
+ base.class_inheritable_accessor :hmac_options
316
+ end
317
+
318
+ module ClassMethods
319
+ # Call with an Active Resource class definition to sign
320
+ # all HTTP requests sent by that class with the provided
321
+ # credentials.
322
+ #
323
+ # Can be called with either a hash or two separate parameters
324
+ # like so:
325
+ #
326
+ # class MyResource < ActiveResource::Base
327
+ # with_auth_hmac("my_access_id", "my_secret")
328
+ # end
329
+ #
330
+ # or
331
+ #
332
+ # class MyOtherResource < ActiveResource::Base
333
+ # with_auth_hmac("my_access_id" => "my_secret")
334
+ # end
335
+ #
336
+ #
337
+ # This has only been tested with Rails 2.1 and since it is virtually a monkey
338
+ # patch of the internals of ActiveResource it might not work with past or
339
+ # future versions.
340
+ #
341
+ def with_auth_hmac(access_id, secret = nil, options = nil)
342
+ if access_id.is_a?(Hash)
343
+ self.hmac_access_id = access_id.keys.first
344
+ self.hmac_secret = access_id[self.hmac_access_id]
345
+ else
346
+ self.hmac_access_id = access_id
347
+ self.hmac_secret = secret
348
+ end
349
+ self.use_hmac = true
350
+ self.hmac_options = options
351
+
352
+ class << self
353
+ alias_method_chain :connection, :hmac
354
+ end
355
+ end
356
+
357
+ def connection_with_hmac(refresh = false) # :nodoc:
358
+ c = connection_without_hmac(refresh)
359
+ c.hmac_access_id = self.hmac_access_id
360
+ c.hmac_secret = self.hmac_secret
361
+ c.use_hmac = self.use_hmac
362
+ c.hmac_options = self.hmac_options
363
+ c
364
+ end
365
+ end
366
+
367
+ module InstanceMethods # :nodoc:
368
+ end
369
+ end
370
+
371
+ module Connection # :nodoc:
372
+ def self.included(base)
373
+ base.send :alias_method_chain, :request, :hmac
374
+ base.class_eval do
375
+ attr_accessor :hmac_secret, :hmac_access_id, :use_hmac, :hmac_options
376
+ end
377
+ end
378
+
379
+ def request_with_hmac(method, path, *arguments)
380
+ if use_hmac && hmac_access_id && hmac_secret
381
+ arguments.last['Date'] = Time.now.httpdate if arguments.last['Date'].nil?
382
+ temp = "Net::HTTP::#{method.to_s.capitalize}".constantize.new(path, arguments.last)
383
+ AuthHMAC.sign!(temp, hmac_access_id, hmac_secret, hmac_options)
384
+ arguments.last['Authorization'] = temp['Authorization']
385
+ end
386
+
387
+ request_without_hmac(method, path, *arguments)
388
+ end
389
+ end
390
+
391
+ unless defined?(ActiveResource)
392
+ begin
393
+ require 'rubygems'
394
+ gem 'activeresource'
395
+ require 'activeresource'
396
+ rescue
397
+ nil
398
+ end
399
+ end
400
+
401
+ if defined?(ActiveResource)
402
+ ActiveResource::Base.send(:include, BaseHmac)
403
+ ActiveResource::Connection.send(:include, Connection)
404
+ end
405
+ end
406
+ end
407
+ end