Bug 33146: Unit tests
[koha-ffzg.git] / t / db_dependent / Auth.t
index 4c29f2c..9c14a0f 100755 (executable)
@@ -10,7 +10,7 @@ use CGI qw ( -utf8 );
 use Test::MockObject;
 use Test::MockModule;
 use List::MoreUtils qw/all any none/;
-use Test::More tests => 15;
+use Test::More tests => 17;
 use Test::Warn;
 use t::lib::Mocks;
 use t::lib::TestBuilder;
@@ -28,18 +28,20 @@ BEGIN {
 
 my $schema  = Koha::Database->schema;
 my $builder = t::lib::TestBuilder->new;
-my $dbh     = C4::Context->dbh;
 
 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
 # handling
 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
 t::lib::Mocks::mock_preference( 'GDPR_Policy', '' ); # Disabled
 
+# To silence useless warnings
+$ENV{REMOTE_ADDR} = '127.0.0.1';
+
 $schema->storage->txn_begin;
 
 subtest 'checkauth() tests' => sub {
 
-    plan tests => 5;
+    plan tests => 8;
 
     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
 
@@ -109,7 +111,117 @@ subtest 'checkauth() tests' => sub {
         is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
     };
 
+    subtest 'Template params tests (password_expired)' => sub {
+
+        plan tests => 1;
+
+        my $password_expired;
+
+        my $patron_class = Test::MockModule->new('Koha::Patron');
+        $patron_class->mock( 'password_expired', sub { return $password_expired; } );
+
+        my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
+        my $password = 'password';
+        t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
+        $patron->set_password( { password => $password } );
+
+        my $cgi_mock = Test::MockModule->new('CGI')->mock( 'request_method', 'POST' );
+        my $cgi = CGI->new;
+        $cgi->param( -name => 'userid',   -value => $patron->userid );
+        $cgi->param( -name => 'password', -value => $password );
+
+        my $auth = Test::MockModule->new( 'C4::Auth' );
+        # Tests will fail if we hit safe_exit
+        $auth->mock( 'safe_exit', sub { return } );
+
+        my ( $userid, $cookie, $sessionID, $flags );
+
+        {
+            t::lib::Mocks::mock_preference( 'DumpTemplateVarsOpac', 1 );
+            # checkauth will redirect and safe_exit if not authenticated and not authorized
+            local *STDOUT;
+            my $stdout;
+            open STDOUT, '>', \$stdout;
+
+            # Password has expired
+            $password_expired = 1;
+            C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } );
+            like( $stdout, qr{'password_has_expired' => 1}, 'password_has_expired is set to 1' );
+
+            close STDOUT;
+        };
+    };
+
+    subtest 'While still logged in, relogin with another user' => sub {
+        plan tests => 6;
+
+        my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
+        my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
+        # Create 'former' session
+        my $session = C4::Auth::get_session();
+        $session->param( 'number',       $patron->id );
+        $session->param( 'id',           $patron->userid );
+        $session->param( 'ip',           '1.2.3.4' );
+        $session->param( 'lasttime',     time() );
+        $session->param( 'interface',    'opac' );
+        $session->flush;
+        my $sessionID = $session->id;
+        C4::Context->_new_userenv($sessionID);
+
+        my ( $return ) = C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
+        is( $return, 'ok', 'Former session in shape now' );
+
+        my $mock1 = Test::MockModule->new('C4::Auth');
+        $mock1->mock( 'safe_exit', sub {} );
+        my $mock2 = Test::MockModule->new('CGI');
+        $mock2->mock( 'request_method', 'POST' );
+        $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
+        my $cgi = CGI->new;
+        my $password = 'Incr3d1blyZtr@ng93$';
+        $patron2->set_password({ password => $password });
+        $cgi->param( -name => 'userid',             -value => $patron2->userid );
+        $cgi->param( -name => 'password',           -value => $password );
+        $cgi->param( -name => 'koha_login_context', -value => 1 );
+        my ( @return, $stdout );
+        {
+            local *STDOUT;
+            local %ENV;
+            $ENV{REMOTE_ADDR} = '1.2.3.4';
+            open STDOUT, '>', \$stdout;
+            @return = C4::Auth::checkauth( $cgi, 0, {} );
+            close STDOUT;
+        }
+        # Note: We can test return values from checkauth here since we mocked the safe_exit after the Redirect 303
+        is( $return[0], $patron2->userid, 'Login of patron2 approved' );
+        isnt( $return[2], $sessionID, 'Did not return previous session ID' );
+        ok( $return[2], 'New session ID not empty' );
+
+        # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
+        $patron2->flags(undef)->store;
+        $session->param( 'number',       $patron->id );
+        $session->param( 'id',           $patron->userid );
+        $session->param( 'interface',    'intranet' );
+        $session->flush;
+        $sessionID = $session->id;
+        C4::Context->_new_userenv($sessionID);
+        $cgi->param( -name => 'userid',             -value => $patron2->userid );
+        $cgi->param( -name => 'password',           -value => $password );
+        $cgi->param( -name => 'koha_login_context', -value => 1 );
+        {
+            local *STDOUT;
+            local %ENV;
+            $ENV{REMOTE_ADDR} = '1.2.3.4';
+            $stdout = q{};
+            open STDOUT, '>', \$stdout;
+            @return = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' ); # patron2 has no catalogue perm
+            close STDOUT;
+        }
+        like( $stdout, qr/You do not have permission to access this page/, 'No permission response' );
+        is( @return, 0, 'checkauth returned failure' );
+    };
+
     subtest 'Two-factor authentication' => sub {
+        plan tests => 18;
 
         my $patron = $builder->build_object(
             { class => 'Koha::Patrons', value => { flags => 1 } } );
@@ -147,7 +259,7 @@ subtest 'checkauth() tests' => sub {
             $logout = 0;
         }
 
-        t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
+        t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
         $patron->auth_method('password')->store;
         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
         is( $userid, $patron->userid, 'Succesful login' );
@@ -160,14 +272,17 @@ subtest 'checkauth() tests' => sub {
         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
         logout($cgi);
 
-        t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 1 );
+        t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' );
+        t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
         $patron->auth_method('password')->store;
         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
         is( $userid, $patron->userid, 'Succesful login' );
         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
         logout($cgi);
 
-        $patron->auth_method('two-factor')->store;
+        $patron->encode_secret('one_secret');
+        $patron->auth_method('two-factor');
+        $patron->store;
         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
         is( $userid, $patron->userid, 'Succesful login' );
         my $session = C4::Auth::get_session($sessionID);
@@ -186,11 +301,74 @@ subtest 'checkauth() tests' => sub {
         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
         is( $userid, $patron->userid, 'Succesful login' );
         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
+        logout($cgi);
 
+        t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enforced' );
+        $patron->auth_method('password')->store;
+        ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
+        is( $userid, $patron->userid, 'Succesful login' );
+        is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' );
+        logout($cgi);
+
+        ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
+        is( $userid, $patron->userid, 'Succesful login at the OPAC' );
+        is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
+
+        #
+        t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
+        $session = C4::Auth::get_session($sessionID);
+        $session->param('waiting-for-2FA', 1);
+        $session->flush;
+        my ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
+        is( $auth_status, 'ok', 'User authenticated, pref was disabled, access OK' );
+        $session->param('waiting-for-2FA', 0);
+        $session->param('waiting-for-2FA-setup', 1);
+        $session->flush;
+        ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
+        is( $auth_status, 'ok', 'User waiting for 2FA setup, pref was disabled, access OK' );
     };
 
-    C4::Context->_new_userenv; # For next tests
+    subtest 'loggedinlibrary permission tests' => sub {
+
+        plan tests => 3;
+        my $staff_user = $builder->build_object(
+            { class => 'Koha::Patrons', value => { flags => 536870916 } } );
+
+        my $branch = $builder->build_object({ class => 'Koha::Libraries' });
+
+        my $password = 'password';
+        t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
+        $staff_user->set_password( { password => $password } );
+        my $cgi = Test::MockObject->new();
+        $cgi->mock( 'cookie', sub { return; } );
+        $cgi->mock(
+            'param',
+            sub {
+                my ( $self, $param ) = @_;
+                if    ( $param eq 'userid' )   { return $staff_user->userid; }
+                elsif ( $param eq 'password' ) { return $password; }
+                elsif ( $param eq 'branch' )   { return $branch->branchcode; }
+                else                           { return; }
+            }
+        );
+
+        $cgi->mock( 'request_method', sub { return 'POST' } );
+        my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
+        my $sesh = C4::Auth::get_session($sessionID);
+        is( $sesh->param('branch'), $branch->branchcode, "If user has permission, they should be able to choose a branch" );
+
+        $staff_user->flags(4)->store->discard_changes;
+        ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
+        $sesh = C4::Auth::get_session($sessionID);
+        is( $sesh->param('branch'), $staff_user->branchcode, "If user has not permission, they should not be able to choose a branch" );
 
+        $staff_user->flags(1)->store->discard_changes;
+        ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
+        $sesh = C4::Auth::get_session($sessionID);
+        is( $sesh->param('branch'), $branch->branchcode, "If user is superlibrarian, they should be able to choose a branch" );
+
+    };
+    C4::Context->_new_userenv; # For next tests
 };
 
 subtest 'track_login_daily tests' => sub {
@@ -246,14 +424,14 @@ subtest 'no_set_userenv parameter tests' => sub {
     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
     $patron->set_password({ password => $password });
 
-    ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
+    ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
     is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
     C4::Context->_new_userenv('DUMMY SESSION');
     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
-    ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
+    ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
-    ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
+    ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
     isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
 };
 
@@ -268,15 +446,15 @@ subtest 'checkpw lockout tests' => sub {
     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
     $patron->set_password({ password => $password });
 
-    my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
+    my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
     ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
-    ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
+    ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
     is( $checkpw, 0, 'checkpw returns false when given wrong password' );
     $patron = $patron->get_from_storage;
     is( $patron->account_locked, 1, "Account is locked from failed login");
-    ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
+    ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
     is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
-    ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
+    ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
     is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
 
 };
@@ -476,7 +654,7 @@ subtest 'Check value of login_attempts in checkpw' => sub {
     $patron->password('123')->store; # yes, deliberately not hashed
 
     is( $patron->account_locked, 0, 'Patron not locked' );
-    my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
+    my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
         # Note: 123 will not be hashed to 123 !
     is( $test[0], 0, 'checkpw should have failed' );
     $patron->discard_changes; # refresh
@@ -484,7 +662,7 @@ subtest 'Check value of login_attempts in checkpw' => sub {
     is( $patron->account_locked, 1, 'Check locked status' );
 
     # And another try to go over the limit: different return value!
-    @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
+    @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
     is( @test, 0, 'checkpw failed again and returns nothing now' );
     $patron->discard_changes; # refresh
     is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
@@ -494,11 +672,11 @@ subtest 'Check value of login_attempts in checkpw' => sub {
     my $auth = Test::MockModule->new( 'C4::Auth' );
     $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
     $patron->login_attempts(0)->store;
-    @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
+    @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
     is( $test[0], 1, 'Build confidence in the mock' );
     $patron->login_attempts(-1)->store;
     is( $patron->account_locked, 1, 'Check administrative lockout' );
-    @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
+    @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
     is( @test, 0, 'checkpw gave red' );
     $patron->discard_changes; # refresh
     is( $patron->login_attempts, -1, 'Still locked out' );
@@ -506,8 +684,25 @@ subtest 'Check value of login_attempts in checkpw' => sub {
     is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
 };
 
+subtest 'Check value of login_attempts in checkpw' => sub {
+    plan tests => 2;
+
+    t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
+    my $patron = $builder->build_object({ class => 'Koha::Patrons' });
+    $patron->set_password({ password => '123', skip_validation => 1 });
+
+    my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
+    is( $test[0], 1, 'Patron authenticated correctly' );
+
+    $patron->password_expiration_date('2020-01-01')->store;
+    @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
+    is( $test[0], -2, 'Patron returned as expired correctly' );
+
+};
+
 subtest '_timeout_syspref' => sub {
-    plan tests => 5;
+
+    plan tests => 6;
 
     t::lib::Mocks::mock_preference('timeout', "100");
     is( C4::Auth::_timeout_syspref, 100, );
@@ -522,7 +717,10 @@ subtest '_timeout_syspref' => sub {
     is( C4::Auth::_timeout_syspref, 10*3600, );
 
     t::lib::Mocks::mock_preference('timeout', "10x");
-    is( C4::Auth::_timeout_syspref, 600, );
+    warning_is
+        { is( C4::Auth::_timeout_syspref, 600, ); }
+        "The value of the system preference 'timeout' is not correct, defaulting to 600",
+        'Bad values throw a warning and fallback to 600';
 };
 
 subtest 'check_cookie_auth' => sub {
@@ -742,4 +940,28 @@ subtest 'Userenv clearing in check_cookie_auth' => sub {
     is( C4::Context->userenv, undef, 'Environment should be cleared again' );
 };
 
+subtest 'create_basic_session tests' => sub {
+    plan tests => 13;
+
+    my $patron = $builder->build_object({ class => 'Koha::Patrons' });
+
+    my $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'opac' });
+
+    isnt($session->id, undef, 'A new sessionID was created');
+    is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' );
+    is( $session->param('id'), $patron->userid, 'Session parameter id matches' );
+    is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' );
+    is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' );
+    is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' );
+    is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' );
+    is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' );
+    is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' );
+    is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' );
+    is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' );
+    is( $session->param('interface'), 'opac', 'Session parameter interface matches' );
+
+    $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'staff' });
+    is( $session->param('interface'), 'intranet', 'Staff interface gets converted to intranet' );
+};
+
 $schema->storage->txn_rollback;