Skip to content

Commit

Permalink
Merge branch 'sliding_windows'
Browse files Browse the repository at this point in the history
* sliding_windows:
  remove ruby-debug and avoid the rbx-require-relative hassle
  implement sliding TFA validation windows
  add failing spec for sliding TFA time windows
  refactor validate_code check in preparation for sliding time windows
  add Spork and Guard to speed up spec feedback
  • Loading branch information
robertwahler committed Jun 22, 2012
2 parents fd561bb + 05ae610 commit 58d9580
Show file tree
Hide file tree
Showing 7 changed files with 229 additions and 61 deletions.
6 changes: 5 additions & 1 deletion Gemfile
Expand Up @@ -45,11 +45,15 @@ gem "ipaddress", "~> 0.8.0"
gem 'uuidtools', "~> 2.1.2"

group :test, :development do
gem "ruby-debug"
gem "rspec-rails", "~> 2.8"
gem "factory_girl_rails", "~> 1.6"
gem "capybara", "~> 1.1"
gem "database_cleaner", "~> 0.7.1"
gem "timecop", "= 0.3.5"
gem "shoulda-matchers", "~> 1.0.0"
# guard
gem "guard", "~> 1.0"
gem "guard-rspec", ">= 0.6"
gem "spork-rails", "~> 3.2.0"
gem "guard-spork", "~> 0.7.1"
end
26 changes: 16 additions & 10 deletions Gemfile.lock
Expand Up @@ -49,7 +49,6 @@ GEM
coffee-script-source
execjs
coffee-script-source (1.2.0)
columnize (0.3.6)
database_cleaner (0.7.1)
diff-lcs (1.1.3)
erubis (2.7.0)
Expand All @@ -61,6 +60,14 @@ GEM
factory_girl (~> 2.6.0)
railties (>= 3.0.0)
ffi (1.0.11)
guard (1.0.2)
ffi (>= 0.5.0)
thor (~> 0.14.6)
guard-rspec (0.7.0)
guard (>= 0.10.0)
guard-spork (0.7.1)
guard (>= 0.10.0)
spork (>= 0.8.4)
hike (1.2.1)
i18n (0.6.0)
ipaddress (0.8.0)
Expand All @@ -70,8 +77,6 @@ GEM
thor (~> 0.14)
json (1.6.5)
json_pure (1.6.5)
linecache (0.46)
rbx-require-relative (> 0.0.4)
mail (2.4.1)
i18n (>= 0.4.0)
mime-types (~> 1.16)
Expand Down Expand Up @@ -103,7 +108,6 @@ GEM
rdoc (~> 3.4)
thor (~> 0.14.6)
rake (0.9.2.2)
rbx-require-relative (0.0.5)
rdoc (3.12)
json (~> 1.4)
rotp (1.3.2)
Expand All @@ -121,11 +125,6 @@ GEM
activesupport (>= 3.0)
railties (>= 3.0)
rspec (~> 2.8.0)
ruby-debug (0.10.4)
columnize (>= 0.1)
ruby-debug-base (~> 0.10.4.0)
ruby-debug-base (0.10.4)
linecache (>= 0.3)
rubyzip (0.9.6.1)
sass (3.1.15)
sass-rails (3.2.4)
Expand All @@ -138,6 +137,10 @@ GEM
json_pure
rubyzip
shoulda-matchers (1.0.0)
spork (1.0.0rc2)
spork-rails (3.2.0)
rails (>= 3.0.0, < 3.3.0)
spork (>= 1.0rc0)
sprockets (2.1.2)
hike (~> 1.2)
rack (~> 1.0)
Expand Down Expand Up @@ -166,16 +169,19 @@ DEPENDENCIES
coffee-rails (~> 3.2.1)
database_cleaner (~> 0.7.1)
factory_girl_rails (~> 1.6)
guard (~> 1.0)
guard-rspec (>= 0.6)
guard-spork (~> 0.7.1)
ipaddress (~> 0.8.0)
jquery-rails
json
rails (= 3.2.1)
rotp (~> 1.3.2)
rqrcode (~> 0.4.2)
rspec-rails (~> 2.8)
ruby-debug
sass-rails (~> 3.2.3)
shoulda-matchers (~> 1.0.0)
spork-rails (~> 3.2.0)
sqlite3
timecop (= 0.3.5)
uglifier (>= 1.0.3)
Expand Down
37 changes: 37 additions & 0 deletions Guardfile
@@ -0,0 +1,37 @@
# starts up/reloads the spork server
guard 'spork', :cucumber_env => { 'RAILS_ENV' => 'test' }, :rspec_env => { 'RAILS_ENV' => 'test' } do
watch('config/application.rb')
watch('config/environment.rb')
watch(%r{^config/environments/.+\.rb$})
watch(%r{^config/initializers/.+\.rb$})
watch('Gemfile')
watch('Gemfile.lock')
watch('spec/spec_helper.rb') { :rspec }
watch('spec/framework_spec_helper.rb') { :rspec }
watch('spec/shoulda_spec_helper.rb') { :rspec }
watch('test/test_helper.rb') { :test_unit }
watch(%r{features/support/}) { :cucumber }
end

group :specs do
guard 'rspec',
:all_after_pass => false,
:all_on_start => false,
:bundler => false,
:cli => '--drb --color --format nested',
:version => 2 do

watch('spec/spec_helper.rb') { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }

watch(%r{^spec/.+_spec\.rb})
watch(%r{^app/(.+)\.rb}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^lib/(.+)\.rb}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb}) { |m| [ "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb" ] }
watch(%r{^app/views/(.+)/}) { |m| "spec/controllers/#{m[1]}_controller_spec.rb" }

watch(%r{^spec/factories/(.*)\.rb} ) { |m| "spec/controllers/%s_controller_spec.rb" % m[1] }
watch(%r{^app/helpers/(.*)/.*} ) { |m| "spec/controllers/%s_controller_spec.rb" % m[1] }
end
end
18 changes: 18 additions & 0 deletions README.markdown
Expand Up @@ -68,6 +68,9 @@ run the RSpec test suite

rspec

for development, start-up the Spork process via Guard

bundle exec guard

### Demo Configuration Options

Expand All @@ -85,6 +88,21 @@ Change length of time the TFA confirmation is valid in app/models/user.rb
12.hours
end

Change the sliding window width from the default of one 30 second window in
app/controllers/user_sessions_controller.rb

# Use a sliding time window to validate tokens. System clock inaccuracy can
# be tolerated at the expense a small decrease in security. A value of 0
# will disable the sliding window
#
# A value of 2 will check tokens in two windows before and after the current
# 30 second window. ie. +/- 60 seconds surrounding the current window.
#
# @return [Integer] width of the window in 30 second increments
def sliding_window_width
1
end

#### Excluding IP Ranges from TFA

Change ApplicationController to allow all logins to bypass TFA
Expand Down
28 changes: 27 additions & 1 deletion app/controllers/user_sessions_controller.rb
Expand Up @@ -47,7 +47,7 @@ def validate
reset_session
flash[:error] = "Two factor confirmation failure count exceeded. Please contact the admin."
redirect_to :root
elsif (validation_code == ROTP::TOTP.new(two_factor_secret).now.to_s)
elsif validate_code(validation_code, two_factor_secret)
session[:two_factor_confirmed_at] = current_user.confirm_two_factor!
flash[:notice] = 'Your session has been confirmed'
redirect_back :root
Expand All @@ -67,4 +67,30 @@ def clear_session
session[:return_to] = return_to if return_to
end

# True if code validates within the sliding window
#
# @return [Boolean]
def validate_code(validation_code, two_factor_secret)
valid_codes = []
valid_codes << ROTP::TOTP.new(two_factor_secret).now.to_s
(1..sliding_window_width).each do |index|
valid_codes << ROTP::TOTP.new(two_factor_secret).at(Time.now.ago(30 * index)).to_s
valid_codes << ROTP::TOTP.new(two_factor_secret).at(Time.now.in(30 * index)).to_s
end

valid_codes.include?(validation_code)
end

# Use a sliding time window to validate tokens. System clock inaccuracy can
# be tolerated at the expense a small decrease in security. A value of 0
# will disable the sliding window
#
# A value of 2 will check tokens in two windows before and after the current
# 30 second window. ie. +/- 60 seconds surrounding the current window.
#
# @return [Integer] width of the window in 30 second increments
def sliding_window_width
1
end

end
51 changes: 42 additions & 9 deletions spec/controllers/user_sessions_controller_spec.rb
Expand Up @@ -131,18 +131,51 @@
end
end


context "with a valid token" do

it "should redirect from confirmation page to the requested page" do
before :each do
session[:return_to] = '/users'
user = find_or_create_user("user")
login_as(user.login, :two_factor_confirm => false)
validation_code = ROTP::TOTP.new(user.two_factor_secret).now.to_s
post :validate, :user_session => { :validation_code => validation_code }
response.should redirect_to('/users')
flash[:notice].should match(/Your session has been confirmed/)
session[:two_factor_confirmed_at].should_not be_nil
session[:two_factor_confirmed_at].should be_nil
end

context "from the current time window" do

it "should redirect from confirmation page to the requested page" do
user = find_or_create_user("user")
login_as(user.login, :two_factor_confirm => false)
validation_code = ROTP::TOTP.new(user.two_factor_secret).now.to_s
post :validate, :user_session => { :validation_code => validation_code }
response.should redirect_to('/users')
flash[:notice].should match(/Your session has been confirmed/)
session[:two_factor_confirmed_at].should_not be_nil
end

end

context "within a sliding time window" do

it "should redirect from confirmation page to the requested page for the previous 30 seconds" do
sliding_window_width = 1
user = find_or_create_user("user")
login_as(user.login, :two_factor_confirm => false)
validation_code = ROTP::TOTP.new(user.two_factor_secret).at(Time.now.ago(30 * sliding_window_width)).to_s
post :validate, :user_session => { :validation_code => validation_code }
response.should redirect_to('/users')
flash[:notice].should match(/Your session has been confirmed/)
session[:two_factor_confirmed_at].should_not be_nil
end

it "should redirect from confirmation page to the requested page for the following 30 seconds" do
sliding_window_width = 1
user = find_or_create_user("user")
login_as(user.login, :two_factor_confirm => false)
validation_code = ROTP::TOTP.new(user.two_factor_secret).at(Time.now.in(30 * sliding_window_width)).to_s
post :validate, :user_session => { :validation_code => validation_code }
response.should redirect_to('/users')
flash[:notice].should match(/Your session has been confirmed/)
session[:two_factor_confirmed_at].should_not be_nil
end

end

it "should reset the two_factor_failure_count" do
Expand Down
124 changes: 84 additions & 40 deletions spec/spec_helper.rb
@@ -1,43 +1,87 @@
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'

require 'authlogic/test_case'
include Authlogic::TestCase

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
include AuthHelper

RSpec.configure do |config|
# Focus specs:
# it "does something", :focus => true do
config.filter_run :focus => true
config.run_all_when_everything_filtered = true

# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr

# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true

# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false

config.before(:suite) do
find_or_create_user("user")
require 'spork'
#uncomment the following line to use spork with the debugger
#require 'spork/ext/ruby-debug'

# --- Instructions ---
# Sort the contents of this file into a Spork.prefork and a Spork.each_run
# block.
#
# The Spork.prefork block is run only once when the spork server is started.
# You typically want to place most of your (slow) initializer code in here, in
# particular, require'ing any 3rd-party gems that you don't normally modify
# during development.
#
# The Spork.each_run block is run each time you run your specs. In case you
# need to load files that tend to change during development, require them here.
# With Rails, your application modules are loaded automatically, so sometimes
# this block can remain empty.
#
# Note: You can modify files loaded *from* the Spork.each_run block without
# restarting the spork server. However, this file itself will not be reloaded,
# so if you change any of the code inside the each_run block, you still need to
# restart the server. In general, if you have non-trivial code in this file,
# it's advisable to move it into a separate file so you can easily edit it
# without restarting spork. (For example, with RSpec, you could move
# non-trivial code into a file spec/support/my_helper.rb, making sure that the
# spec/support/* files are require'd from inside the each_run block.)
#
# Any code that is left outside the two blocks will be run during preforking
# *and* during each_run -- that's probably not what you want.
#
# These instructions should self-destruct in 10 seconds. If they don't, feel
# free to delete them.

# Loading more in this block will cause your tests to run faster. However,
# if you change any configuration or code from libraries loaded here, you'll
# need to restart spork for it take effect.
Spork.prefork do

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'

require 'authlogic/test_case'
include Authlogic::TestCase

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
include AuthHelper

RSpec.configure do |config|
# Focus specs:
# it "does something", :focus => true do
config.filter_run :focus => true
config.run_all_when_everything_filtered = true

# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr

# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true

# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false

config.before(:suite) do
find_or_create_user("user")
end

end
end

# This code will be run each time you run your specs.
Spork.each_run do
FactoryGirl.reload
end

0 comments on commit 58d9580

Please sign in to comment.