diff options
Diffstat (limited to 'users/test')
-rw-r--r-- | users/test/factories.rb | 3 | ||||
-rw-r--r-- | users/test/functional/helper_methods_test.rb | 2 | ||||
-rw-r--r-- | users/test/functional/test_helpers_test.rb | 38 | ||||
-rw-r--r-- | users/test/functional/users_controller_test.rb | 12 | ||||
-rw-r--r-- | users/test/functional/v1/sessions_controller_test.rb | 18 | ||||
-rw-r--r-- | users/test/functional/v1/users_controller_test.rb | 8 | ||||
-rw-r--r-- | users/test/integration/api/account_flow_test.rb | 42 | ||||
-rwxr-xr-x | users/test/integration/api/python/flow_with_srp.py | 96 | ||||
-rw-r--r-- | users/test/integration/browser/account_test.rb | 20 | ||||
-rw-r--r-- | users/test/support/auth_test_helper.rb | 9 | ||||
-rw-r--r-- | users/test/support/stub_record_helper.rb | 5 | ||||
-rw-r--r-- | users/test/unit/email_aliases_test.rb | 66 | ||||
-rw-r--r-- | users/test/unit/email_test.rb | 19 | ||||
-rw-r--r-- | users/test/unit/identity_test.rb | 86 | ||||
-rw-r--r-- | users/test/unit/local_email_test.rb | 34 | ||||
-rw-r--r-- | users/test/unit/user_test.rb | 23 |
16 files changed, 343 insertions, 138 deletions
diff --git a/users/test/factories.rb b/users/test/factories.rb index 777704b..c87e290 100644 --- a/users/test/factories.rb +++ b/users/test/factories.rb @@ -18,4 +18,7 @@ FactoryGirl.define do end end end + + factory :token + end diff --git a/users/test/functional/helper_methods_test.rb b/users/test/functional/helper_methods_test.rb index 2b2375c..44226ae 100644 --- a/users/test/functional/helper_methods_test.rb +++ b/users/test/functional/helper_methods_test.rb @@ -11,7 +11,7 @@ class HelperMethodsTest < ActionController::TestCase # we test them right in here... include ApplicationController._helpers - # they all reference the controller. + # the helpers all reference the controller. def controller @controller end diff --git a/users/test/functional/test_helpers_test.rb b/users/test/functional/test_helpers_test.rb new file mode 100644 index 0000000..9bd01ad --- /dev/null +++ b/users/test/functional/test_helpers_test.rb @@ -0,0 +1,38 @@ +# +# There are a few test helpers for dealing with login etc. +# We test them here and also document their behaviour. +# + +require 'test_helper' + +class TestHelpersTest < ActionController::TestCase + tests ApplicationController # testing no controller in particular + + def test_login_stubs_warden + login + assert_equal @current_user, request.env['warden'].user + end + + def test_login_token_authenticates + login + assert_equal @current_user, @controller.send(:token_authenticate) + end + + def test_login_stubs_token + login + assert @token + assert_equal @current_user, @token.user + end + + def test_login_adds_token_header + login + token_present = @controller.authenticate_with_http_token do |token, options| + assert_equal @token.id, token + end + # authenticate_with_http_token just returns nil and does not + # execute the block if there is no token. So we have to also + # ensure it was run: + assert token_present + end +end + diff --git a/users/test/functional/users_controller_test.rb b/users/test/functional/users_controller_test.rb index 0ce5cc2..96ae48c 100644 --- a/users/test/functional/users_controller_test.rb +++ b/users/test/functional/users_controller_test.rb @@ -59,19 +59,23 @@ class UsersControllerTest < ActionController::TestCase assert_access_denied end - test "show for non-existing user" do + test "may not show non-existing user without auth" do nonid = 'thisisnotanexistinguserid' - # when unauthenticated: get :show, :id => nonid assert_access_denied(true, false) + end - # when authenticated but not admin: + test "may not show non-existing user without admin" do + nonid = 'thisisnotanexistinguserid' login + get :show, :id => nonid assert_access_denied + end - # when authenticated as admin: + test "redirect admin to user list for non-existing user" do + nonid = 'thisisnotanexistinguserid' login :is_admin? => true get :show, :id => nonid assert_response :redirect diff --git a/users/test/functional/v1/sessions_controller_test.rb b/users/test/functional/v1/sessions_controller_test.rb index 0c4e325..ff9fca1 100644 --- a/users/test/functional/v1/sessions_controller_test.rb +++ b/users/test/functional/v1/sessions_controller_test.rb @@ -7,7 +7,7 @@ class V1::SessionsControllerTest < ActionController::TestCase setup do @request.env['HTTP_HOST'] = 'api.lvh.me' - @user = stub_record :user + @user = stub_record :user, {}, true @client_hex = 'a123' end @@ -48,13 +48,22 @@ class V1::SessionsControllerTest < ActionController::TestCase assert_response :success assert json_response.keys.include?("id") assert json_response.keys.include?("token") + assert token = Token.find(json_response['token']) + assert_equal @user.id, token.user_id end - test "logout should reset warden user" do + test "logout should reset session" do expect_warden_logout delete :destroy - assert_response :redirect - assert_redirected_to root_url + assert_response 204 + end + + test "logout should destroy token" do + login + expect_warden_logout + @token.expects(:destroy) + delete :destroy + assert_response 204 end def expect_warden_logout @@ -65,5 +74,4 @@ class V1::SessionsControllerTest < ActionController::TestCase request.env['warden'].expects(:logout) end - end diff --git a/users/test/functional/v1/users_controller_test.rb b/users/test/functional/v1/users_controller_test.rb index 0d44e50..a330bf3 100644 --- a/users/test/functional/v1/users_controller_test.rb +++ b/users/test/functional/v1/users_controller_test.rb @@ -5,7 +5,9 @@ class V1::UsersControllerTest < ActionController::TestCase test "user can change settings" do user = find_record :user changed_attribs = record_attributes_for :user_with_settings - user.expects(:update_attributes).with(changed_attribs) + account_settings = stub + account_settings.expects(:update).with(changed_attribs) + AccountSettings.expects(:new).with(user).returns(account_settings) login user put :update, :user => changed_attribs, :id => user.id, :format => :json @@ -18,7 +20,9 @@ class V1::UsersControllerTest < ActionController::TestCase test "admin can update user" do user = find_record :user changed_attribs = record_attributes_for :user_with_settings - user.expects(:update_attributes).with(changed_attribs) + account_settings = stub + account_settings.expects(:update).with(changed_attribs) + AccountSettings.expects(:new).with(user).returns(account_settings) login :is_admin? => true put :update, :user => changed_attribs, :id => user.id, :format => :json diff --git a/users/test/integration/api/account_flow_test.rb b/users/test/integration/api/account_flow_test.rb index 4c94389..e41befa 100644 --- a/users/test/integration/api/account_flow_test.rb +++ b/users/test/integration/api/account_flow_test.rb @@ -5,6 +5,7 @@ class AccountFlowTest < RackTest setup do @login = "integration_test_user" + Identity.find_by_address(@login + '@' + APP_CONFIG[:domain]).tap{|i| i.destroy if i} User.find_by_login(@login).tap{|u| u.destroy if u} @password = "srp, verify me!" @srp = SRP::Client.new @login, :password => @password @@ -18,7 +19,10 @@ class AccountFlowTest < RackTest end teardown do - @user.destroy if @user + if @user.reload + @user.identity.destroy + @user.destroy + end Warden.test_reset! end @@ -74,25 +78,45 @@ class AccountFlowTest < RackTest assert_nil server_auth end + test "update password via api" do + @srp.authenticate(self) + @password = "No! Verify me instead." + @srp = SRP::Client.new @login, :password => @password + @user_params = { + # :login => @login, + :password_verifier => @srp.verifier.to_s(16), + :password_salt => @srp.salt.to_s(16) + } + put "http://api.lvh.me:3000/1/users/" + @user.id + '.json', + :user => @user_params, + :format => :json + server_auth = @srp.authenticate(self) + assert last_response.successful? + assert_nil server_auth["errors"] + assert server_auth["M2"] + end + test "update user" do server_auth = @srp.authenticate(self) test_public_key = 'asdlfkjslfdkjasd' original_login = @user.login new_login = 'zaph' + User.find_by_login(new_login).try(:destroy) + Identity.by_address.key(new_login + '@' + APP_CONFIG[:domain]).each do |identity| + identity.destroy + end put "http://api.lvh.me:3000/1/users/" + @user.id + '.json', :user => {:public_key => test_public_key, :login => new_login}, :format => :json - @user.reload - assert_equal test_public_key, @user.public_key - assert_equal new_login, @user.login + assert last_response.successful? + assert_equal test_public_key, Identity.for(@user).keys[:pgp] + # does not change login if no password_verifier is present + assert_equal original_login, @user.login # eventually probably want to remove most of this into a non-integration functional test # should not overwrite public key: put "http://api.lvh.me:3000/1/users/" + @user.id + '.json', :user => {:blee => :blah}, :format => :json - @user.reload - assert_equal test_public_key, @user.public_key + assert_equal test_public_key, Identity.for(@user).keys[:pgp] # should overwrite public key: put "http://api.lvh.me:3000/1/users/" + @user.id + '.json', :user => {:public_key => nil}, :format => :json - # TODO: not sure why i need this, but when public key is removed, the DB is updated but @user.reload doesn't seem to actually reload. - @user = User.find(@user.id) # @user.reload - assert_nil @user.public_key + assert_nil Identity.for(@user).keys[:pgp] end end diff --git a/users/test/integration/api/python/flow_with_srp.py b/users/test/integration/api/python/flow_with_srp.py index 7b741d6..9fc168b 100755 --- a/users/test/integration/api/python/flow_with_srp.py +++ b/users/test/integration/api/python/flow_with_srp.py @@ -11,68 +11,86 @@ import binascii safe_unhexlify = lambda x: binascii.unhexlify(x) if (len(x) % 2 == 0) else binascii.unhexlify('0'+x) +# using globals for now +# server = 'https://dev.bitmask.net/1' +server = 'http://api.lvh.me:3000/1' + +def run_tests(): + login = 'test_' + id_generator() + password = id_generator() + id_generator() + usr = srp.User( login, password, srp.SHA256, srp.NG_1024 ) + print_and_parse(signup(login, password)) + + auth = print_and_parse(authenticate(usr)) + verify_or_debug(auth, usr) + assert usr.authenticated() + + usr = change_password(auth['id'], login, auth['token']) + + auth = print_and_parse(authenticate(usr)) + verify_or_debug(auth, usr) + # At this point the authentication process is complete. + assert usr.authenticated() + # let's have some random name def id_generator(size=6, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) -# using globals for a start -server = 'https://api.bitmask.net:4430/1' -login = id_generator() -password = id_generator() + id_generator() - -# print ' username = "' + login + '"' -# print ' password = "' + password + '"' - # log the server communication def print_and_parse(response): - print response.request.method + ': ' + response.url - print " " + json.dumps(response.request.data) + request = response.request + print request.method + ': ' + response.url + if hasattr(request, 'data'): + print " " + json.dumps(response.request.data) print " -> " + response.text - return json.loads(response.text) + try: + return json.loads(response.text) + except ValueError: + return None -def signup(session): +def signup(login, password): salt, vkey = srp.create_salted_verification_key( login, password, srp.SHA256, srp.NG_1024 ) - # print ' salt = "' + binascii.hexlify(salt) + '"' - # print ' v = "' + binascii.hexlify(vkey) + '"' user_params = { 'user[login]': login, 'user[password_verifier]': binascii.hexlify(vkey), 'user[password_salt]': binascii.hexlify(salt) } - return session.post(server + '/users.json', data = user_params, verify = False) + return requests.post(server + '/users.json', data = user_params, verify = False) -usr = srp.User( login, password, srp.SHA256, srp.NG_1024 ) +def change_password(user_id, login, token): + password = id_generator() + id_generator() + salt, vkey = srp.create_salted_verification_key( login, password, srp.SHA256, srp.NG_1024 ) + user_params = { + 'user[password_verifier]': binascii.hexlify(vkey), + 'user[password_salt]': binascii.hexlify(salt) + } + auth_headers = { 'Authorization': 'Token token="' + token + '"'} + print user_params + print_and_parse(requests.put(server + '/users/' + user_id + '.json', data = user_params, verify = False, headers = auth_headers)) + return srp.User( login, password, srp.SHA256, srp.NG_1024 ) -def authenticate(session, login): + +def authenticate(usr): + session = requests.session() uname, A = usr.start_authentication() - # print ' aa = "' + binascii.hexlify(A) + '"' params = { 'login': uname, 'A': binascii.hexlify(A) } init = print_and_parse(session.post(server + '/sessions', data = params, verify=False)) - # print ' b = "' + init['b'] + '"' - # print ' bb = "' + init['B'] + '"' M = usr.process_challenge( safe_unhexlify(init['salt']), safe_unhexlify(init['B']) ) - # print ' m = "' + binascii.hexlify(M) + '"' - return session.put(server + '/sessions/' + login, verify = False, + return session.put(server + '/sessions/' + uname, verify = False, data = {'client_auth': binascii.hexlify(M)}) -session = requests.session() -user = print_and_parse(signup(session)) - -# SRP signup would happen here and calculate M hex -auth = print_and_parse(authenticate(session, user['login'])) -if ( 'errors' in auth ): - print ' u = "%x"' % usr.u - print ' x = "%x"' % usr.x - print ' v = "%x"' % usr.v - print ' S = "%x"' % usr.S - print ' K = "' + binascii.hexlify(usr.K) + '"' - print ' M = "%x"' % usr.M -else: - usr.verify_session( safe_unhexlify(auth["M2"]) ) - -# At this point the authentication process is complete. -assert usr.authenticated() +def verify_or_debug(auth, usr): + if ( 'errors' in auth ): + print ' u = "%x"' % usr.u + print ' x = "%x"' % usr.x + print ' v = "%x"' % usr.v + print ' S = "%x"' % usr.S + print ' K = "' + binascii.hexlify(usr.K) + '"' + print ' M = "' + binascii.hexlify(usr.M) + '"' + else: + usr.verify_session( safe_unhexlify(auth["M2"]) ) +run_tests() diff --git a/users/test/integration/browser/account_test.rb b/users/test/integration/browser/account_test.rb index ce63baf..b412980 100644 --- a/users/test/integration/browser/account_test.rb +++ b/users/test/integration/browser/account_test.rb @@ -20,4 +20,24 @@ class AccountTest < BrowserIntegrationTest assert_equal '/', current_path end + # trying to seed an invalid A for srp login + test "detects attempt to circumvent SRP" do + user = FactoryGirl.create :user + visit '/sessions/new' + fill_in 'Username', with: user.login + fill_in 'Password', with: "password" + inject_malicious_js + click_on 'Log In' + assert page.has_content?("Invalid random key") + assert page.has_no_content?("Welcome") + end + + def inject_malicious_js + page.execute_script <<-EOJS + var calc = new srp.Calculate(); + calc.A = function(_a) {return "00";}; + calc.S = calc.A; + srp.session = new srp.Session(null, calc); + EOJS + end end diff --git a/users/test/support/auth_test_helper.rb b/users/test/support/auth_test_helper.rb index 555b5db..47147fc 100644 --- a/users/test/support/auth_test_helper.rb +++ b/users/test/support/auth_test_helper.rb @@ -13,8 +13,9 @@ module AuthTestHelper if user_or_method_hash.respond_to?(:reverse_merge) user_or_method_hash.reverse_merge! :is_admin? => false end - @current_user = stub_record(:user, user_or_method_hash, true) + @current_user = stub_record(:user, user_or_method_hash) request.env['warden'] = stub :user => @current_user + request.env['HTTP_AUTHORIZATION'] = header_for_token_auth return @current_user end @@ -37,6 +38,12 @@ module AuthTestHelper end end + protected + + def header_for_token_auth + @token = find_record(:token, :user => @current_user) + ActionController::HttpAuthentication::Token.encode_credentials @token.id + end end class ActionController::TestCase diff --git a/users/test/support/stub_record_helper.rb b/users/test/support/stub_record_helper.rb index 8aa1973..5bccb66 100644 --- a/users/test/support/stub_record_helper.rb +++ b/users/test/support/stub_record_helper.rb @@ -7,9 +7,8 @@ module StubRecordHelper # If no record is given but a hash or nil will create a stub based on # that instead and returns the stub. # - def find_record(factory, attribs_hash = {}) - attribs_hash = attribs_hash.reverse_merge(:id => Random.rand(10000).to_s) - record = stub_record factory, attribs_hash + def find_record(factory, record_or_attribs_hash = {}) + record = stub_record factory, record_or_attribs_hash, true klass = record.class finder = klass.respond_to?(:find_by_param) ? :find_by_param : :find klass.stubs(finder).with(record.to_param.to_s).returns(record) diff --git a/users/test/unit/email_aliases_test.rb b/users/test/unit/email_aliases_test.rb deleted file mode 100644 index 86d14aa..0000000 --- a/users/test/unit/email_aliases_test.rb +++ /dev/null @@ -1,66 +0,0 @@ -require 'test_helper' - -class EmailAliasTest < ActiveSupport::TestCase - - setup do - @user = FactoryGirl.build :user - @alias = "valid_alias" - # make sure no existing records are in the way... - User.find_by_login_or_alias(@alias).try(:destroy) - end - - test "no email aliases set in the beginning" do - assert_equal [], @user.email_aliases - end - - test "adding email alias through params" do - @user.attributes = {:email_aliases_attributes => {"0" => {:email => @alias}}} - assert @user.changed? - assert @user.save - assert_equal @alias, @user.email_aliases.first.username - end - - test "adding email alias directly" do - @user.email_aliases.build :email => @alias - assert @user.save - assert_equal @alias, @user.email_aliases.first.username - end - - test "duplicated email aliases are invalid" do - @user.email_aliases.build :email => @alias - @user.save - assert_invalid_alias @alias - end - - test "email alias needs to be different from other peoples login" do - other_user = FactoryGirl.create :user, :login => @alias - assert_invalid_alias @alias - other_user.destroy - end - - test "email needs to be different from other peoples email aliases" do - other_user = FactoryGirl.create :user, :email_aliases_attributes => {'1' => @alias} - assert_invalid_alias @alias - other_user.destroy - end - - test "login is invalid as email alias" do - @user.login = @alias - assert_invalid_alias @alias - end - - test "find user by email alias" do - @user.email_aliases.build :email => @alias - assert @user.save - assert_equal @user, User.find_by_login_or_alias(@alias) - assert_equal @user, User.find_by_alias(@alias) - assert_nil User.find_by_login(@alias) - end - - def assert_invalid_alias(string) - email_alias = @user.email_aliases.build :email => string - assert !email_alias.valid? - assert !@user.valid? - end - -end diff --git a/users/test/unit/email_test.rb b/users/test/unit/email_test.rb new file mode 100644 index 0000000..7cfbc84 --- /dev/null +++ b/users/test/unit/email_test.rb @@ -0,0 +1,19 @@ +require 'test_helper' + +class EmailTest < ActiveSupport::TestCase + + test "valid format" do + email = Email.new(email_string) + assert email.valid? + end + + test "validates format" do + email = Email.new("email") + assert !email.valid? + assert_equal ["needs to be a valid email address"], email.errors[:email] + end + + def email_string + @email_string ||= Faker::Internet.email + end +end diff --git a/users/test/unit/identity_test.rb b/users/test/unit/identity_test.rb new file mode 100644 index 0000000..bf24f02 --- /dev/null +++ b/users/test/unit/identity_test.rb @@ -0,0 +1,86 @@ +require 'test_helper' + +class IdentityTest < ActiveSupport::TestCase + + setup do + @user = FactoryGirl.create(:user) + end + + teardown do + @user.destroy + end + + test "initial identity for a user" do + id = Identity.for(@user) + assert_equal @user.email_address, id.address + assert_equal @user.email_address, id.destination + assert_equal @user, id.user + end + + test "add alias" do + id = Identity.for @user, address: alias_name + assert_equal LocalEmail.new(alias_name), id.address + assert_equal @user.email_address, id.destination + assert_equal @user, id.user + end + + test "add forward" do + id = Identity.for @user, destination: forward_address + assert_equal @user.email_address, id.address + assert_equal Email.new(forward_address), id.destination + assert_equal @user, id.user + end + + test "forward alias" do + id = Identity.for @user, address: alias_name, destination: forward_address + assert_equal LocalEmail.new(alias_name), id.address + assert_equal Email.new(forward_address), id.destination + assert_equal @user, id.user + id.save + end + + test "prevents duplicates" do + id = Identity.create_for @user, address: alias_name, destination: forward_address + dup = Identity.build_for @user, address: alias_name, destination: forward_address + assert !dup.valid? + assert_equal ["This alias already exists"], dup.errors[:base] + end + + test "validates availability" do + other_user = FactoryGirl.create(:user) + id = Identity.create_for @user, address: alias_name, destination: forward_address + taken = Identity.build_for other_user, address: alias_name + assert !taken.valid? + assert_equal ["This email has already been taken"], taken.errors[:base] + other_user.destroy + end + + test "setting and getting pgp key" do + id = Identity.for(@user) + id.set_key(:pgp, pgp_key_string) + assert_equal pgp_key_string, id.keys[:pgp] + end + + test "querying pgp key via couch" do + id = Identity.for(@user) + id.set_key(:pgp, pgp_key_string) + id.save + view = Identity.pgp_key_by_email.key(id.address) + assert_equal 1, view.rows.count + assert result = view.rows.first + assert_equal id.address, result["key"] + assert_equal id.keys[:pgp], result["value"] + end + + def alias_name + @alias_name ||= Faker::Internet.user_name + end + + def forward_address + @forward_address ||= Faker::Internet.email + end + + def pgp_key_string + @pgp_key ||= "DUMMY PGP KEY ... "+SecureRandom.base64(4096) + end +end diff --git a/users/test/unit/local_email_test.rb b/users/test/unit/local_email_test.rb new file mode 100644 index 0000000..b25f46f --- /dev/null +++ b/users/test/unit/local_email_test.rb @@ -0,0 +1,34 @@ +require 'test_helper' + +class LocalEmailTest < ActiveSupport::TestCase + + test "appends domain" do + local = LocalEmail.new(handle) + assert_equal LocalEmail.new(email), local + assert local.valid? + end + + test "returns handle" do + local = LocalEmail.new(email) + assert_equal handle, local.handle + end + + test "prints full email" do + local = LocalEmail.new(handle) + assert_equal email, "#{local}" + end + + test "validates domain" do + local = LocalEmail.new(Faker::Internet.email) + assert !local.valid? + assert_equal ["needs to end in @#{LocalEmail.domain}"], local.errors[:email] + end + + def handle + @handle ||= Faker::Internet.user_name + end + + def email + handle + "@" + APP_CONFIG[:domain] + end +end diff --git a/users/test/unit/user_test.rb b/users/test/unit/user_test.rb index c8c837b..89ee749 100644 --- a/users/test/unit/user_test.rb +++ b/users/test/unit/user_test.rb @@ -56,23 +56,30 @@ class UserTest < ActiveSupport::TestCase other_user.destroy end - test "login needs to be different from other peoples email aliases" do + test "login needs to be unique amongst aliases" do other_user = FactoryGirl.create :user - other_user.email_aliases.build :email => @user.login - other_user.save + Identity.create_for other_user, address: @user.login assert !@user.valid? other_user.destroy end + test "deprecated public key api still works" do + key = SecureRandom.base64(4096) + @user.public_key = key + assert_equal key, @user.public_key + end + test "pgp key view" do - @user.public_key = SecureRandom.base64(4096) - @user.save + key = SecureRandom.base64(4096) + identity = Identity.create_for @user + identity.set_key('pgp', key) + identity.save - view = User.pgp_key_by_handle.key(@user.login) + view = Identity.pgp_key_by_email.key(@user.email_address) assert_equal 1, view.rows.count assert result = view.rows.first - assert_equal @user.login, result["key"] - assert_equal @user.public_key, result["value"] + assert_equal @user.email_address, result["key"] + assert_equal key, result["value"] end end |