rack-api-key 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/.rvmrc ADDED
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env bash
2
+
3
+ # This is an RVM Project .rvmrc file, used to automatically load the ruby
4
+ # development environment upon cd'ing into the directory
5
+
6
+ # First we specify our desired <ruby>[@<gemset>], the @gemset name is optional,
7
+ # Only full ruby name is supported here, for short names use:
8
+ # echo "rvm use 1.9.3" > .rvmrc
9
+ environment_id="ruby-1.9.3-p374@rack-api-key"
10
+
11
+ # Uncomment the following lines if you want to verify rvm version per project
12
+ # rvmrc_rvm_version="1.18.5 (stable)" # 1.10.1 seams as a safe start
13
+ # eval "$(echo ${rvm_version}.${rvmrc_rvm_version} | awk -F. '{print "[[ "$1*65536+$2*256+$3" -ge "$4*65536+$5*256+$6" ]]"}' )" || {
14
+ # echo "This .rvmrc file requires at least RVM ${rvmrc_rvm_version}, aborting loading."
15
+ # return 1
16
+ # }
17
+
18
+ # First we attempt to load the desired environment directly from the environment
19
+ # file. This is very fast and efficient compared to running through the entire
20
+ # CLI and selector. If you want feedback on which environment was used then
21
+ # insert the word 'use' after --create as this triggers verbose mode.
22
+ if [[ -d "${rvm_path:-$HOME/.rvm}/environments"
23
+ && -s "${rvm_path:-$HOME/.rvm}/environments/$environment_id" ]]
24
+ then
25
+ \. "${rvm_path:-$HOME/.rvm}/environments/$environment_id"
26
+ [[ -s "${rvm_path:-$HOME/.rvm}/hooks/after_use" ]] &&
27
+ \. "${rvm_path:-$HOME/.rvm}/hooks/after_use" || true
28
+ else
29
+ # If the environment file has not yet been created, use the RVM CLI to select.
30
+ rvm --create "$environment_id" || {
31
+ echo "Failed to create RVM environment '${environment_id}'."
32
+ return 1
33
+ }
34
+ fi
35
+
36
+ # If you use bundler, this might be useful to you:
37
+ # if [[ -s Gemfile ]] && {
38
+ # ! builtin command -v bundle >/dev/null ||
39
+ # builtin command -v bundle | GREP_OPTIONS= \grep $rvm_path/bin/bundle >/dev/null
40
+ # }
41
+ # then
42
+ # printf "%b" "The rubygem 'bundler' is not installed. Installing it now.\n"
43
+ # gem install bundler
44
+ # fi
45
+ # if [[ -s Gemfile ]] && builtin command -v bundle >/dev/null
46
+ # then
47
+ # bundle install | GREP_OPTIONS= \grep -vE '^Using|Your bundle is complete'
48
+ # fi
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in rack-api-key.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 Nick Zalabak
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # RackApiKey
2
+
3
+ RackApiKey is a middleware that relies on the client submitting requests
4
+ with a header named "X-API-KEY" storing their private API key as the value.
5
+ The middleware will then intercept the request, read the value from the named
6
+ header and call the given "proc" used for API key lookup. The API key lookup
7
+ should only return a value if there is an exact match for the value stored in
8
+ the named API key header.
9
+ If such a API key exists, the middleware will pass the request onward and also
10
+ set a new value in the request representing the authenticated API key. Otherwise
11
+ the middleware will return a HTTP status of 401, and a plain text message
12
+ notifying the calling requestor that they are not authorized.
13
+
14
+ ## Installation
15
+
16
+ Add this line to your application's Gemfile:
17
+
18
+ gem 'rack-api-key'
19
+
20
+ And then execute:
21
+
22
+ $ bundle
23
+
24
+ Or install it yourself as:
25
+
26
+ $ gem install rack-api-key
27
+
28
+ ## Usage
29
+
30
+ ```ruby
31
+ Rack::Builder.new do
32
+ map '/' do
33
+ use RackApiKey, :api_key_proc => Proc.new { |val| ApiKey.find(val) }
34
+ run lambda { |env| [200, {"Content-Type" => "text/html"}, "Testing Middleware"] }
35
+ end
36
+
37
+ map "/all-options" do
38
+ use RackApiKey,
39
+ :api_key_proc => Proc.new { |val| ApiKey.find(val) },
40
+ :rack_api_key => "account.api.key",
41
+ :header_key => "HTTP_X_CUSTOM_API_HEADER"
42
+ run lambda { |env| [200, {"Content-Type" => "text/html"}, "Testing Middleware"] }
43
+ end
44
+ end
45
+ ```
data/Rakefile ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
3
+ require 'rspec/core/rake_task'
4
+
5
+ RSpec::Core::RakeTask.new(:spec)
6
+
7
+ task :default => :spec
@@ -0,0 +1,83 @@
1
+ require "rack-api-key/version"
2
+
3
+ ##
4
+ # RackApiKey is a middleware that relies on the client submitting requests
5
+ # with a header named "X-API-KEY" storing their private API key as the value.
6
+ # The middleware will then intercept the request, read the value from the named
7
+ # header and call the given "proc" used for API key lookup. The API key lookup
8
+ # should only return a value if there is an exact match for the value stored in
9
+ # the named API key header.
10
+ # If such a API key exists, the middleware will pass the request onward and also
11
+ # set a new value in the request representing the authenticated API key. Otherwise
12
+ # the middleware will return a HTTP status of 401, and a plain text message
13
+ # notifying the calling requestor that they are not authorized.
14
+ class RackApiKey
15
+
16
+ ##
17
+ # ==== Options
18
+ # * +:api_key_proc+ - **REQUIRED** A proc that is intended to lookup the API key in your datastore.
19
+ # The given proc should take an argument, namely the value of the API key header.
20
+ # There is no default value for this option and will raise a
21
+ # NotImplementedError if left unspecified.
22
+ # * +:rack_api_key+ - A way to override the key's name set in the request
23
+ # on successful authentication. The default value is
24
+ # "rack_api_key".
25
+ # * +:header_key+ - A way to override the header's name used to store the API key.
26
+ # The default value is "HTTP_X_API_KEY".
27
+ #
28
+ # ==== Example
29
+ # use RackApiKey,
30
+ # :api_key_proc => Proc.new { |key| ApiKey.where(:key => key).first },
31
+ # :rack_api_key => "authenticated.api.key",
32
+ # :header_key => "HTTP_X_SECRET_API_KEY"
33
+ def initialize(app, options = {})
34
+ @app = app
35
+ default_options = {
36
+ :header_key => "HTTP_X_API_KEY",
37
+ :rack_api_key => "rack_api_key",
38
+ :api_key_proc => Proc.new { raise NotImplementedError.new("Caller must implement a way to lookup an API key.") }
39
+ }
40
+ @options = default_options.merge(options)
41
+ end
42
+
43
+ def call(env)
44
+ api_header_val = env[@options[:header_key]]
45
+ api_key_lookup_val = @options[:api_key_proc].call(api_header_val)
46
+
47
+ if valid_api_key?(api_header_val, api_key_lookup_val)
48
+ rack_api_key_request_setter(env, api_key_lookup_val)
49
+ @app.call(env)
50
+ else
51
+ unauthorized_api_key
52
+ end
53
+ end
54
+
55
+ ##
56
+ # Sets the API key lookup value in the request. Intentionally left here
57
+ # if anyone wants to change or override what does or does not get set
58
+ # in the request.
59
+ def rack_api_key_request_setter(env, api_key_lookup_val)
60
+ env[@options[:rack_api_key]] = api_key_lookup_val
61
+ end
62
+
63
+ ##
64
+ # Returns a 401 HTTP status code when an API key is not found or is not
65
+ # authorized. Intentionally left here if anyone wants to override this
66
+ # functionality, specifically change the format of the message or the
67
+ # media type.
68
+ def unauthorized_api_key
69
+ body_text = "The API key provided is not authorized."
70
+ [401, {'Content-Type' => 'text/plain; charset=utf-8',
71
+ 'Content-Length' => body_text.size.to_s}, [body_text]]
72
+ end
73
+
74
+ ##
75
+ # Checks if the API key header value is present and the API key
76
+ # that was returned from the API key proc is present.
77
+ # Intentionally left here is anyone wants to override this functionality.
78
+ def valid_api_key?(api_header_val, api_key_lookup_val)
79
+ !api_header_val.nil? && api_header_val != "" &&
80
+ !api_key_lookup_val.nil? && api_key_lookup_val != ""
81
+ end
82
+
83
+ end
@@ -0,0 +1,3 @@
1
+ class RackApiKey
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,21 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/rack-api-key/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Nick Zalabak"]
6
+ gem.email = ["techwhizbang@gmail.com"]
7
+ gem.description = %q{RackApiKey is a middleware that enables simple API key authentication}
8
+ gem.summary = %q{RackApiKey is a middleware that enables simple API key authentication}
9
+ gem.homepage = "https://github.com/techwhizbang/rack-api-key"
10
+
11
+ gem.files = `git ls-files`.split($\)
12
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
13
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
14
+ gem.name = "rack-api-key"
15
+ gem.require_paths = ["lib"]
16
+ gem.version = RackApiKey::VERSION
17
+ gem.add_dependency %q<rack>, [">= 1.0"]
18
+ gem.add_development_dependency %q<rake>, ["0.9.2.2"]
19
+ gem.add_development_dependency %q<rspec>, ["~> 2.12.0"]
20
+ gem.add_development_dependency %q<rack-test>, ["~> 0.6.2"]
21
+ end
@@ -0,0 +1,117 @@
1
+ require 'spec_helper'
2
+
3
+ describe RackApiKey do
4
+ include Rack::Test::Methods
5
+
6
+ class Account; end
7
+
8
+ class ApiKey
9
+
10
+ attr_reader :value
11
+
12
+ def initialize(value)
13
+ @value = value
14
+ end
15
+
16
+ def self.find(value)
17
+ nil
18
+ end
19
+
20
+ def account
21
+ Account.new
22
+ end
23
+
24
+ end
25
+
26
+ # simple test app for the middleware test
27
+ def app
28
+ Rack::Builder.new do
29
+ map '/' do
30
+ use RackApiKey, :api_key_proc => Proc.new { |val| ApiKey.find(val) }
31
+ run lambda { |env| [200, {"Content-Type" => "text/html"}, "Testing Middleware"] }
32
+ end
33
+
34
+ map "/no-api-proc" do
35
+ use RackApiKey
36
+ run lambda { |env| [200, {"Content-Type" => "text/html"}, "Testing Middleware"] }
37
+ end
38
+
39
+ map "/all-options" do
40
+ use RackApiKey,
41
+ :api_key_proc => Proc.new { |val| ApiKey.find(val) },
42
+ :rack_api_key => "account.api.key",
43
+ :header_key => "HTTP_X_CUSTOM_API_HEADER"
44
+ run lambda { |env| [200, {"Content-Type" => "text/html"}, "Testing Middleware"] }
45
+ end
46
+
47
+ end
48
+ end
49
+
50
+ context "when using the predefined default middleware options" do
51
+
52
+ it 'attempts to find the ApiKey with the header value' do
53
+ ApiKey.should_receive(:find).with("SECRET API KEY")
54
+ get "/", {}, "HTTP_X_API_KEY" => "SECRET API KEY"
55
+ end
56
+
57
+ it 'responds with a 200 upon successful authorization' do
58
+ ApiKey.stub(:find).and_return(ApiKey.new("SECRET API KEY"))
59
+ get "/", {}, "HTTP_X_API_KEY" => "SECRET API KEY"
60
+ last_response.ok?.should be_true
61
+ end
62
+
63
+ it 'responds with a 401 when the ApiKey is not found' do
64
+ ApiKey.stub(:find).and_return(nil)
65
+ get "/", {}, "HTTP_X_API_KEY" => "SECRET API KEY"
66
+ last_response.status.should == 401
67
+ end
68
+
69
+ it 'responds with a 401 when the header is not set' do
70
+ header("HTTP_X_API_KEY", nil)
71
+ get "/"
72
+ last_response.status.should == 401
73
+ end
74
+
75
+ it 'responds with a JSON formatted error message' do
76
+ header("HTTP_X_API_KEY", nil)
77
+ get "/"
78
+ last_response.body.should == "The API key provided is not authorized."
79
+ end
80
+
81
+ it 'sets the api key in the env' do
82
+ ApiKey.stub(:find).and_return(api_key = ApiKey.new("SECRET API KEY"))
83
+ get "/", {}, "HTTP_X_API_KEY" => "SECRET API KEY"
84
+ last_request.env['rack_api_key'].should == api_key
85
+ end
86
+
87
+ end
88
+
89
+ context "when the API key lookup proc is not provided" do
90
+
91
+ it 'raises an error' do
92
+ expect { get "/no-api-proc", {}, {} }.to raise_error(NotImplementedError, "Caller must implement a way to lookup an API key.")
93
+ end
94
+
95
+ end
96
+
97
+ context "when all the options are specified" do
98
+
99
+ it 'attempts to find the ApiKey with the header value' do
100
+ ApiKey.should_receive(:find).with("SECRET API KEY")
101
+ get "/all-options", {}, "HTTP_X_CUSTOM_API_HEADER" => "SECRET API KEY"
102
+ end
103
+
104
+ it 'responds with a 200 upon successful authorization' do
105
+ ApiKey.stub(:find).and_return(ApiKey.new("SECRET API KEY"))
106
+ get "/all-options", {}, "HTTP_X_CUSTOM_API_HEADER" => "SECRET API KEY"
107
+ last_response.ok?.should be_true
108
+ end
109
+
110
+ it 'sets the api key in the env' do
111
+ ApiKey.stub(:find).and_return(api_key = ApiKey.new("SECRET API KEY"))
112
+ get "/all-options", {}, "HTTP_X_CUSTOM_API_HEADER" => "SECRET API KEY"
113
+ last_request.env['account.api.key'].should == api_key
114
+ end
115
+
116
+ end
117
+ end
@@ -0,0 +1,6 @@
1
+ require 'rubygems'
2
+ require 'rspec'
3
+ require 'rake'
4
+ require "rack/test"
5
+
6
+ require File.expand_path(File.dirname(__FILE__) + "/../lib/rack-api-key")
metadata ADDED
@@ -0,0 +1,128 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rack-api-key
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Nick Zalabak
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2013-04-04 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rack
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '1.0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ! '>='
28
+ - !ruby/object:Gem::Version
29
+ version: '1.0'
30
+ - !ruby/object:Gem::Dependency
31
+ name: rake
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - '='
36
+ - !ruby/object:Gem::Version
37
+ version: 0.9.2.2
38
+ type: :development
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - '='
44
+ - !ruby/object:Gem::Version
45
+ version: 0.9.2.2
46
+ - !ruby/object:Gem::Dependency
47
+ name: rspec
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ~>
52
+ - !ruby/object:Gem::Version
53
+ version: 2.12.0
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ~>
60
+ - !ruby/object:Gem::Version
61
+ version: 2.12.0
62
+ - !ruby/object:Gem::Dependency
63
+ name: rack-test
64
+ requirement: !ruby/object:Gem::Requirement
65
+ none: false
66
+ requirements:
67
+ - - ~>
68
+ - !ruby/object:Gem::Version
69
+ version: 0.6.2
70
+ type: :development
71
+ prerelease: false
72
+ version_requirements: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ~>
76
+ - !ruby/object:Gem::Version
77
+ version: 0.6.2
78
+ description: RackApiKey is a middleware that enables simple API key authentication
79
+ email:
80
+ - techwhizbang@gmail.com
81
+ executables: []
82
+ extensions: []
83
+ extra_rdoc_files: []
84
+ files:
85
+ - .gitignore
86
+ - .rvmrc
87
+ - Gemfile
88
+ - LICENSE
89
+ - README.md
90
+ - Rakefile
91
+ - lib/rack-api-key.rb
92
+ - lib/rack-api-key/version.rb
93
+ - rack-api-key.gemspec
94
+ - spec/rack_api_key_spec.rb
95
+ - spec/spec_helper.rb
96
+ homepage: https://github.com/techwhizbang/rack-api-key
97
+ licenses: []
98
+ post_install_message:
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ none: false
104
+ requirements:
105
+ - - ! '>='
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ segments:
109
+ - 0
110
+ hash: 3957032321281409751
111
+ required_rubygems_version: !ruby/object:Gem::Requirement
112
+ none: false
113
+ requirements:
114
+ - - ! '>='
115
+ - !ruby/object:Gem::Version
116
+ version: '0'
117
+ segments:
118
+ - 0
119
+ hash: 3957032321281409751
120
+ requirements: []
121
+ rubyforge_project:
122
+ rubygems_version: 1.8.25
123
+ signing_key:
124
+ specification_version: 3
125
+ summary: RackApiKey is a middleware that enables simple API key authentication
126
+ test_files:
127
+ - spec/rack_api_key_spec.rb
128
+ - spec/spec_helper.rb