Browse files

Release 1.0.0

* pulled from patch for Faraday directly
  • Loading branch information...
0 parents commit 2106498d6817343512db52b8c46741d572fedc9e @mtodd committed Jun 20, 2011
Showing with 478 additions and 0 deletions.
  1. +2 −0 .gitignore
  2. +8 −0 Gemfile
  3. +21 −0 LICENSE.md
  4. +29 −0 README.md
  5. +137 −0 Rakefile
  6. +70 −0 faraday-auth-hmac.gemspec
  7. +94 −0 lib/faraday/auth-hmac.rb
  8. +75 −0 test/auth-hmac_test.rb
  9. +42 −0 test/helper.rb
2 .gitignore
@@ -0,0 +1,2 @@
+.bundle
+Gemfile.lock
8 Gemfile
@@ -0,0 +1,8 @@
+source 'http://rubygems.org'
+
+gemspec
+
+group :development do
+ gem 'tzinfo', '~> 0.3.28'
+ gem 'activesupport', '~> 2.3'
+end
21 LICENSE.md
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2011 Matt Todd
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
29 README.md
@@ -0,0 +1,29 @@
+# Faraday AuthHMAC
+## HMAC Signing for Faraday Requests
+
+Enables signing your requests (from Faraday) with AuthHMAC.
+
+## Usage
+
+``` ruby
+require 'faraday'
+require 'faraday/auth-hmac'
+
+c = Faraday.new do |b|
+ b.request :auth_hmac # enables request signing
+ b.adapter :net_http
+end
+
+c.get('http://localhost/') do |r|
+ # signs the request with the access_id and the secret
+ r.sign! 'access_id', 'secret'
+end
+```
+
+## Contributing
+
+* Fork
+* Work on a topic branch
+* Write tests
+* Add/fix/etc
+* Create a Pull Request
137 Rakefile
@@ -0,0 +1,137 @@
+require 'rubygems'
+require 'rake'
+require 'date'
+
+#############################################################################
+#
+# Helper functions
+#
+#############################################################################
+
+def name
+ @name ||= Dir['*.gemspec'].first.split('.').first
+end
+
+def version
+ line = File.read("lib/faraday/auth-hmac.rb")[/^\s*VERSION\s*=\s*.*/]
+ line.match(/.*VERSION\s*=\s*['"](.*)['"]/)[1]
+end
+
+def date
+ Date.today.to_s
+end
+
+def rubyforge_project
+ name
+end
+
+def gemspec_file
+ "#{name}.gemspec"
+end
+
+def gem_file
+ "#{name}-#{version}.gem"
+end
+
+def replace_header(head, header_name)
+ head.sub!(/(\.#{header_name}\s*= ').*'/) { "#{$1}#{send(header_name)}'"}
+end
+
+#############################################################################
+#
+# Standard tasks
+#
+#############################################################################
+
+task :default => :test
+
+require 'rake/testtask'
+Rake::TestTask.new(:test) do |test|
+ test.libs << 'lib' << 'test'
+ test.pattern = 'test/**/*_test.rb'
+ test.verbose = true
+end
+
+require 'rake/rdoctask'
+Rake::RDocTask.new do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = "#{name} #{version}"
+ rdoc.rdoc_files.include('README*')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
+
+desc "Open an irb session preloaded with this library"
+task :console do
+ sh "irb -rubygems -r ./lib/faraday/auth-hmac.rb"
+end
+
+#############################################################################
+#
+# Custom tasks (add your own tasks here)
+#
+#############################################################################
+
+
+
+#############################################################################
+#
+# Packaging tasks
+#
+#############################################################################
+
+desc "Create tag v#{version} and build and push #{gem_file} to Rubygems"
+task :release => :build do
+ unless `git branch` =~ /^\* master$/
+ puts "You must be on the master branch to release!"
+ exit!
+ end
+ sh "git commit --allow-empty -a -m 'Release #{version}'"
+ sh "git tag v#{version}"
+ sh "git push origin master"
+ sh "git push origin v#{version}"
+ sh "gem push pkg/#{name}-#{version}.gem"
+end
+
+desc "Build #{gem_file} into the pkg directory"
+task :build => :gemspec do
+ sh "mkdir -p pkg"
+ sh "gem build #{gemspec_file}"
+ sh "mv #{gem_file} pkg"
+end
+
+desc "Generate #{gemspec_file}"
+task :gemspec => :validate do
+ # read spec file and split out manifest section
+ spec = File.read(gemspec_file)
+ head, manifest, tail = spec.split(" # = MANIFEST =\n")
+
+ # replace name version and date
+ replace_header(head, :name)
+ replace_header(head, :version)
+ replace_header(head, :date)
+ #comment this out if your rubyforge_project has a different name
+ replace_header(head, :rubyforge_project)
+
+ # determine file list from git ls-files
+ files = `git ls-files`.
+ split("\n").
+ sort.
+ reject { |file| file =~ /^\./ }.
+ reject { |file| file =~ /^(rdoc|pkg)/ }.
+ map { |file| " #{file}" }.
+ join("\n")
+
+ # piece file back together and write
+ manifest = " s.files = %w[\n#{files}\n ]\n"
+ spec = [head, manifest, tail].join(" # = MANIFEST =\n")
+ File.open(gemspec_file, 'w') { |io| io.write(spec) }
+ puts "Updated #{gemspec_file}"
+end
+
+desc "Validate #{gemspec_file}"
+task :validate do
+ unless Dir['VERSION*'].empty?
+ puts "A `VERSION` file at root level violates Gem best practices."
+ exit!
+ end
+end
70 faraday-auth-hmac.gemspec
@@ -0,0 +1,70 @@
+## This is the rakegem gemspec template. Make sure you read and understand
+## all of the comments. Some sections require modification, and others can
+## be deleted if you don't need them. Once you understand the contents of
+## this file, feel free to delete any comments that begin with two hash marks.
+## You can find comprehensive Gem::Specification documentation, at
+## http://docs.rubygems.org/read/chapter/20
+Gem::Specification.new do |s|
+ s.specification_version = 2 if s.respond_to? :specification_version=
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.rubygems_version = '1.3.5'
+
+ ## Leave these as is they will be modified for you by the rake gemspec task.
+ ## If your rubyforge_project name is different, then edit it and comment out
+ ## the sub! line in the Rakefile
+ s.name = 'faraday-auth-hmac'
+ s.version = '1.0.0'
+ s.date = '2011-06-20'
+ s.rubyforge_project = 'faraday-auth-hmac'
+
+ ## Make sure your summary is short. The description may be as long
+ ## as you like.
+ s.summary = "Faraday AuthHMAC Request Signing Middelware"
+ s.description = "Signs Faraday requests with AuthHMAC"
+
+ ## List the primary authors. If there are a bunch of authors, it's probably
+ ## better to set the email to an email list or something. If you don't have
+ ## a custom homepage, consider using your GitHub URL or the like.
+ s.authors = ["Matt Todd"]
+ s.email = 'chiology@gmail.com'
+ s.homepage = 'http://github.com/mtodd/faraday-auth-hmac'
+
+ ## This gets added to the $LOAD_PATH so that 'lib/NAME.rb' can be required as
+ ## require 'NAME.rb' or'/lib/NAME/file.rb' can be as require 'NAME/file.rb'
+ s.require_paths = %w[lib]
+
+ ## Specify any RDoc options here. You'll want to add your README and
+ ## LICENSE files to the extra_rdoc_files list.
+ s.rdoc_options = ["--charset=UTF-8"]
+ s.extra_rdoc_files = %w[README LICENSE]
+
+ ## List your runtime dependencies here. Runtime dependencies are those
+ ## that are needed for an end user to actually USE your code.
+ s.add_dependency('faraday', ["~> 0.7.2"])
+ s.add_dependency('dnclabs-auth-hmac', ["~> 1.1.1"])
+
+ ## List your development dependencies here. Development dependencies are
+ ## those that are only needed during development
+ s.add_development_dependency('test-unit', ["~> 2.3"])
+ s.add_development_dependency('leftright', ["~> 0.9"])
+
+ ## Leave this section as-is. It will be automatically generated from the
+ ## contents of your Git repository via the gemspec task. DO NOT REMOVE
+ ## THE MANIFEST COMMENTS, they are used as delimiters by the task.
+ # = MANIFEST =
+ s.files = %w[
+ Gemfile
+ LICENSE.md
+ README.md
+ Rakefile
+ faraday-auth-hmac.gemspec
+ lib/faraday/auth-hmac.rb
+ test/auth-hmac_test.rb
+ test/helper.rb
+ ]
+ # = MANIFEST =
+
+ ## Test files will be grabbed from the file list. Make sure the path glob
+ ## matches what you actually use.
+ s.test_files = s.files.select { |path| path =~ /^test\/test_.*\.rb/ }
+end
94 lib/faraday/auth-hmac.rb
@@ -0,0 +1,94 @@
+require 'faraday'
+require 'faraday/request'
+
+require 'auth-hmac'
+
+module Faraday
+ class Request
+
+ register_lookup_modules :auth_hmac => :AuthHMAC
+
+ attr_accessor :sign_with
+
+ # Sign the request with the specified `access_id` and `secret`.
+ def sign!(access_id, secret)
+ AuthHMAC.keys[access_id] = secret
+ self.sign_with = access_id
+ end
+
+ # Include the `sign_with` property to ensure the request is signed with
+ # the specified `access_id`.
+ alias_method :original_to_env, :to_env
+ def to_env(connection)
+ original_to_env(connection).merge(:sign_with => self.sign_with)
+ end
+
+ # Sign your request using AuthHMAC.
+ #
+ # @connection.get('http://localhost/') do |req|
+ # req.sign! 'access_id', 'secret'
+ # req.body = 'abc'
+ # end
+ #
+ # This adds the Authorization, Content-MD5, and Date headers.
+ #
+ # This middleware can be added and nothing will happen unless the `sign!`
+ # method is called (as in the example above).
+ #
+ class AuthHMAC < Faraday::Middleware
+ VERSION = '1.0.0'
+ AUTH_HEADER = "Authorization".freeze
+
+ # Modified CanonicalString to know how to pull from the Faraday-specific
+ # env hash.
+ class CanonicalString < ::AuthHMAC::CanonicalString
+ def request_method(request)
+ request[:method].to_s.upcase
+ end
+ def request_body(request)
+ request[:body]
+ end
+ def request_path(request)
+ URI.parse(request[:url]).path
+ end
+ def request_path(request, authenticate_referrer)
+ return super if authenticate_referrer
+ URI.parse(request[:url]).path
+ end
+ def headers(request)
+ request[:request_headers]
+ end
+ end
+
+ class << self
+ attr_accessor :keys, :options
+ end
+ self.keys = {}
+ self.options = {:service_id => "FaradayHMAC", :signature => CanonicalString}
+
+ def self.auth
+ ::AuthHMAC.new(keys, options)
+ end
+ def auth
+ self.class.auth
+ end
+
+ def sign!(env, sign_with)
+ self.auth.sign!(env, sign_with)
+
+ # AuthHMAC doesn't set the Authorization header in the
+ # `request_headers` hash.
+ env[:request_headers][AUTH_HEADER] = env.delete(AUTH_HEADER)
+ end
+
+ def call(env)
+ if sign_with = env.delete(:sign_with)
+ sign!(env, sign_with)
+ end
+
+ @app.call(env)
+ end
+
+ end
+ end
+end
75 test/auth-hmac_test.rb
@@ -0,0 +1,75 @@
+require File.expand_path(File.join(File.dirname(__FILE__), 'helper'))
+# require 'rack/utils'
+
+class AuthHMACMiddlewareTest < Faraday::TestCase
+ def setup
+ Faraday::Request::AuthHMAC.keys.clear
+ @access_id, @secret = "id", "secret"
+ @connection = Faraday.new :url => 'http://sushi.com/api'
+ @request = Faraday::Request.create(:get) do |req|
+ req.url 'foo.json'
+ req.body = "test"
+ end
+ generate_env!
+ end
+
+ def test_auth_hmac_skips_when_sign_is_not_called
+ call(@env)
+ assert_nil @env[:request_headers]['Authorization']
+ end
+
+ def test_request_will_instruct_middleware_to_sign_if_told_to
+ assert_nil @env[:sign_with]
+
+ @request.sign! @access_id, @secret
+ generate_env!
+ assert_equal @access_id, @env[:sign_with]
+ end
+
+ def test_request_instructed_to_sign_a_request_will_result_in_a_correctly_signed_request
+ @env[:sign_with] = @access_id
+ klass.keys = {@access_id => @secret}
+
+ call(@env)
+ assert signed?(@env, @access_id, @secret), "should be signed"
+ end
+
+ def test_a_signed_request_includes_appropriate_headers
+ @request.sign! @access_id, @secret
+ generate_env!
+ call(@env)
+
+ %w(Authorization Content-MD5 Date).each do |header|
+ assert_not_nil @env[:request_headers][header], "should have #{header} header"
+ end
+ end
+
+ protected
+
+ def klass
+ Faraday::Request::AuthHMAC
+ end
+
+ def call(env)
+ klass.new(lambda{|_|}).call(env)
+ end
+
+ def generate_env!
+ @env = @request.to_env(@connection)
+ end
+
+ # Based on the `authenticated?` method in auth-hmac.
+ # https://github.com/dnclabs/auth-hmac/blob/master/lib/auth-hmac.rb#L252
+ def signed?(env, access_id, secret)
+ auth = klass.auth
+ rx = Regexp.new("#{klass.options[:service_id]} ([^:]+):(.+)$")
+ if md = rx.match(env[:request_headers][klass::AUTH_HEADER])
+ access_key_id = md[1]
+ hmac = md[2]
+ !secret.nil? && hmac == auth.signature(env, secret)
+ else
+ false
+ end
+ end
+
+end
42 test/helper.rb
@@ -0,0 +1,42 @@
+require 'rubygems'
+require 'test/unit'
+
+require 'bundler'
+Bundler.setup(:default, :development)
+
+require 'time'
+
+require 'active_support/core_ext/object/blank'
+require 'active_support/time_with_zone'
+
+if ENV['LEFTRIGHT']
+ begin
+ require 'leftright'
+ rescue LoadError
+ puts "Run `gem install leftright` to install leftright."
+ end
+end
+
+unless $LOAD_PATH.include? 'lib'
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
+ $LOAD_PATH.unshift(File.join($LOAD_PATH.first, '..', 'lib'))
+end
+
+require 'faraday'
+require 'faraday/auth-hmac'
+
+begin
+ require 'ruby-debug'
+rescue LoadError
+ # ignore
+else
+ Debugger.start
+end
+
+module Faraday
+ class TestCase < Test::Unit::TestCase
+ def test_default
+ assert true
+ end unless defined? ::MiniTest
+ end
+end

0 comments on commit 2106498

Please sign in to comment.