3 # This Koha test module is a stub!
4 # Add more tests here!!!
12 use List::MoreUtils qw/all any none/;
13 use Test::More tests => 17;
16 use t::lib::TestBuilder;
20 use Koha::AuthUtils qw( hash_password );
21 use Koha::DateUtils qw( dt_from_string );
24 use Koha::Auth::TwoFactorAuth;
27 use_ok('C4::Auth', qw( checkauth haspermission track_login_daily checkpw get_template_and_user checkpw_hash ));
30 my $schema = Koha::Database->schema;
31 my $builder = t::lib::TestBuilder->new;
33 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
35 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
36 t::lib::Mocks::mock_preference( 'GDPR_Policy', '' ); # Disabled
38 # To silence useless warnings
39 $ENV{REMOTE_ADDR} = '127.0.0.1';
41 $schema->storage->txn_begin;
43 subtest 'checkauth() tests' => sub {
47 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
49 # Mock a CGI object with real userid param
50 my $cgi = Test::MockObject->new();
55 if ( $var eq 'userid' ) { return $patron->userid; }
58 $cgi->mock( 'cookie', sub { return; } );
59 $cgi->mock( 'request_method', sub { return 'POST' } );
61 my $authnotrequired = 1;
62 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
64 is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
66 my $db_user_id = C4::Context->config('user');
67 my $db_user_pass = C4::Context->config('pass');
68 $cgi = Test::MockObject->new();
69 $cgi->mock( 'cookie', sub { return; } );
70 $cgi->mock( 'param', sub {
71 my ( $self, $param ) = @_;
72 if ( $param eq 'userid' ) { return $db_user_id; }
73 elsif ( $param eq 'password' ) { return $db_user_pass; }
76 $cgi->mock( 'request_method', sub { return 'POST' } );
77 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
78 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
80 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
82 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
83 ok( !$is_allowed, 'DB user should not have any permissions');
85 subtest 'Prevent authentication when sending credential via GET' => sub {
89 my $patron = $builder->build_object(
90 { class => 'Koha::Patrons', value => { flags => 1 } } );
91 my $password = set_weak_password($patron);
92 $cgi = Test::MockObject->new();
93 $cgi->mock( 'cookie', sub { return; } );
97 my ( $self, $param ) = @_;
98 if ( $param eq 'userid' ) { return $patron->userid; }
99 elsif ( $param eq 'password' ) { return $password; }
104 $cgi->mock( 'request_method', sub { return 'POST' } );
105 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
106 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
108 $cgi->mock( 'request_method', sub { return 'GET' } );
109 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
110 is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
113 subtest 'Template params tests (password_expired)' => sub {
117 my $password_expired;
119 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
121 my $password = set_weak_password($patron);
122 $patron->password_expiration_date( dt_from_string->subtract(days => 1) )->store;
124 my $cgi_mock = Test::MockModule->new('CGI');
125 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
127 # Simulating the login form submission
128 $cgi->param( 'userid', $patron->userid );
129 $cgi->param( 'password', $password );
131 my ( $userid, $cookie, $sessionID, $flags, $template ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
132 is( $template->{VARS}->{password_has_expired}, 1 );
135 subtest 'Reset auth state when changing users' => sub {
137 #NOTE: It's easiest to detect this when changing to a non-existent user, since
138 #that should trigger a redirect to login (instead of returning a session cookie)
140 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => undef } } );
142 my $session = C4::Auth::get_session();
143 $session->param( 'number', $patron->id );
144 $session->param( 'id', $patron->userid );
145 $session->param( 'ip', '1.2.3.4' );
146 $session->param( 'lasttime', time() );
147 $session->param( 'interface', 'intranet' );
149 my $sessionID = $session->id;
150 C4::Context->_new_userenv($sessionID);
153 C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
154 is( $return, 'ok', 'Patron authenticated' );
156 my $mock2 = Test::MockModule->new('CGI');
157 $mock2->mock( 'request_method', 'POST' );
158 $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
161 $cgi->param( -name => 'userid', -value => 'Bond' );
162 $cgi->param( -name => 'password', -value => 'James Bond' );
163 $cgi->param( -name => 'koha_login_context', -value => 1 );
164 my ( $userid, $cookie, $flags, $template );
165 ( $userid, $cookie, $sessionID, $flags, $template ) =
166 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
167 is( $template->{VARS}->{loginprompt}, 1, 'Changing to non-existent user causes a redirect to login' );
170 subtest 'While still logged in, relogin with another user' => sub {
173 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
174 my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
175 # Create 'former' session
176 my $session = C4::Auth::get_session();
177 $session->param( 'number', $patron->id );
178 $session->param( 'id', $patron->userid );
179 $session->param( 'ip', '1.2.3.4' );
180 $session->param( 'lasttime', time() );
181 $session->param( 'interface', 'opac' );
183 my $previous_sessionID = $session->id;
184 C4::Context->_new_userenv($previous_sessionID);
186 my ( $return ) = C4::Auth::check_cookie_auth( $previous_sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
187 is( $return, 'ok', 'Former session in shape now' );
189 my $mock1 = Test::MockModule->new('C4::Auth');
190 $mock1->mock( 'safe_exit', sub {} );
191 my $mock2 = Test::MockModule->new('CGI');
192 $mock2->mock( 'request_method', 'POST' );
193 $mock2->mock( 'cookie', sub { return $previous_sessionID; } ); # oversimplified..
195 my $password = 'Incr3d1blyZtr@ng93$';
196 $patron2->set_password({ password => $password });
197 $cgi->param( -name => 'userid', -value => $patron2->userid );
198 $cgi->param( -name => 'password', -value => $password );
199 $cgi->param( -name => 'koha_login_context', -value => 1 );
200 my ( $userid, $cookie, $sessionID, $flags, $template ) =
201 C4::Auth::checkauth( $cgi, 0, {}, 'opac', undef, undef, { do_not_print => 1 } );
202 is( $userid, $patron2->userid, 'Login of patron2 approved' );
203 isnt( $sessionID, $previous_sessionID, 'Did not return previous session ID' );
204 ok( $sessionID, 'New session ID not empty' );
206 # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
207 $patron2->flags(undef)->store;
208 $session->param( 'number', $patron->id );
209 $session->param( 'id', $patron->userid );
210 $session->param( 'interface', 'intranet' );
212 $previous_sessionID = $session->id;
213 C4::Context->_new_userenv($previous_sessionID);
214 $cgi->param( -name => 'userid', -value => $patron2->userid );
215 $cgi->param( -name => 'password', -value => $password );
216 $cgi->param( -name => 'koha_login_context', -value => 1 );
217 ( $userid, $cookie, $sessionID, $flags, $template ) =
218 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
219 is( $template->{VARS}->{nopermission}, 1, 'No permission response' );
222 subtest 'Two-factor authentication' => sub {
224 my $patron = $builder->build_object(
225 { class => 'Koha::Patrons', value => { flags => 1 } } );
226 my $password = 'password';
227 $patron->set_password( { password => $password } );
228 $cgi = Test::MockObject->new();
231 our ( $logout, $sessionID, $verified );
235 my ( $self, $param ) = @_;
236 if ( $param eq 'userid' ) { return $patron->userid; }
237 elsif ( $param eq 'password' ) { return $password; }
238 elsif ( $param eq 'otp_token' ) { return $otp_token; }
239 elsif ( $param eq 'logout.x' ) { return $logout; }
243 $cgi->mock( 'request_method', sub { return 'POST' } );
244 $cgi->mock( 'cookie', sub { return $sessionID } );
246 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
247 $two_factor_auth->mock( 'verify', sub {$verified} );
249 my ( $userid, $cookie, $flags );
250 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
256 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
260 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
261 $patron->auth_method('password')->store;
262 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
263 is( $userid, $patron->userid, 'Succesful login' );
264 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
267 $patron->auth_method('two-factor')->store;
268 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
269 is( $userid, $patron->userid, 'Succesful login' );
270 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
273 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 1 );
274 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
275 $patron->auth_method('password')->store;
276 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
277 is( $userid, $patron->userid, 'Succesful login' );
278 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
281 $patron->encode_secret('one_secret');
282 $patron->auth_method('two-factor');
284 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
285 is( $userid, $patron->userid, 'Succesful login' );
286 my $session = C4::Auth::get_session($sessionID);
287 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
290 $otp_token = "wrong";
292 $patron->auth_method('two-factor')->store;
293 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
294 is( $userid, $patron->userid, 'Succesful login' );
295 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
299 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
300 is( $userid, $patron->userid, 'Succesful login' );
301 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
304 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
305 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
306 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
308 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
311 C4::Context->_new_userenv; # For next tests
315 subtest 'track_login_daily tests' => sub {
319 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
320 my $userid = $patron->userid;
322 $patron->lastseen( undef );
325 my $cache = Koha::Caches->get_instance();
326 my $cache_key = "track_login_" . $patron->userid;
327 $cache->clear_from_cache($cache_key);
329 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
331 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
333 C4::Auth::track_login_daily( $userid );
334 $patron->_result()->discard_changes();
335 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
337 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
338 my $last_seen = $patron->lastseen;
339 C4::Auth::track_login_daily( $userid );
340 $patron->_result()->discard_changes();
341 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
343 $cache->clear_from_cache($cache_key);
344 C4::Auth::track_login_daily( $userid );
345 $patron->_result()->discard_changes();
346 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
348 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
349 $patron->lastseen( undef )->store;
350 $cache->clear_from_cache($cache_key);
351 C4::Auth::track_login_daily( $userid );
352 $patron->_result()->discard_changes();
353 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
357 subtest 'no_set_userenv parameter tests' => sub {
361 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
362 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
364 my $password = set_weak_password($patron);
366 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
367 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
368 C4::Context->_new_userenv('DUMMY SESSION');
369 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
370 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
371 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
372 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
373 ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
374 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
377 subtest 'checkpw lockout tests' => sub {
381 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
382 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
383 my $password = set_weak_password($patron);
384 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
386 my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
387 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
388 ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
389 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
390 $patron = $patron->get_from_storage;
391 is( $patron->account_locked, 1, "Account is locked from failed login");
392 ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
393 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
394 ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
395 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
399 # get_template_and_user tests
401 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
403 sub MockedCheckauth {
404 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
406 my $userid = 'cobain';
408 # we don't need to bother about permissions for this test
410 superlibrarian => 1, acquisition => 0,
412 catalogue => 1, circulate => 0,
413 coursereserves => 0, editauthorities => 0,
415 parameters => 0, permissions => 0,
416 plugins => 0, reports => 0,
417 reserveforothers => 0, serials => 0,
418 staffaccess => 0, tools => 0,
422 my $session_cookie = $query->cookie(
423 -name => 'CGISESSID',
428 return ( $userid, [ $session_cookie ], $sessionID, $flags );
431 # Mock checkauth, build the scenario
432 my $auth = Test::MockModule->new( 'C4::Auth' );
433 $auth->mock( 'checkauth', \&MockedCheckauth );
435 # Make sure 'EnableOpacSearchHistory' is set
436 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
437 # Enable es-ES for the OPAC and staff interfaces
438 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
439 t::lib::Mocks::mock_preference('language','en,es-ES');
441 # we need a session cookie
442 $ENV{"SERVER_PORT"} = 80;
443 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
445 my $query = CGI->new;
446 $query->param('language','es-ES');
448 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
450 template_name => "about.tt",
453 authnotrequired => 1,
454 flagsrequired => { catalogue => 1 },
459 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
460 'BZ9735: the cookies array is flat' );
462 # new query, with non-existent language (we only have en and es-ES)
463 $query->param('language','tomas');
465 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
467 template_name => "about.tt",
470 authnotrequired => 1,
471 flagsrequired => { catalogue => 1 },
476 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
477 'BZ9735: invalid language, it is not set');
479 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
480 'BZ9735: invalid language, then default to en');
482 for my $template_name (
484 ../../../../../../../../../../../../../../../etc/passwd
485 test/../../../../../../../../../../../../../../etc/passwd
487 test/does_not_finished_by_tt_t
491 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
493 template_name => $template_name,
496 authnotrequired => 1,
497 flagsrequired => { catalogue => 1 },
501 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
503 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
505 template_name => 'errors/errorpage.tt',
508 authnotrequired => 1,
509 flagsrequired => { catalogue => 1 },
512 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
513 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
515 # Regression test for env opac search limit override
516 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
517 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
519 ( $template, $loggedinuser, $cookies) = get_template_and_user(
521 template_name => 'opac-main.tt',
524 authnotrequired => 1,
527 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
528 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
530 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
532 ( $template, $loggedinuser, $cookies) = get_template_and_user(
534 template_name => 'opac-main.tt',
537 authnotrequired => 1,
540 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
541 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
542 ok(defined($template->{VARS}->{'csrf_token'}), "CSRF token returned");
544 delete $ENV{"HTTP_COOKIE"};
547 # Check that there is always an OPACBaseURL set.
548 my $input = CGI->new();
549 my ( $template1, $borrowernumber, $cookie );
550 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
552 template_name => "opac-detail.tt",
555 authnotrequired => 1,
559 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
560 'OPACBaseURL is in OPAC template' );
563 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
565 template_name => "catalogue/detail.tt",
568 authnotrequired => 1,
572 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
573 'OPACBaseURL is in Staff template' );
575 my $hash1 = hash_password('password');
576 my $hash2 = hash_password('password');
578 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
579 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
581 subtest 'Check value of login_attempts in checkpw' => sub {
584 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
586 # Only interested here in regular login
590 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
591 $patron->login_attempts(2);
592 $patron->password('123')->store; # yes, deliberately not hashed
594 is( $patron->account_locked, 0, 'Patron not locked' );
595 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
596 # Note: 123 will not be hashed to 123 !
597 is( $test[0], 0, 'checkpw should have failed' );
598 $patron->discard_changes; # refresh
599 is( $patron->login_attempts, 3, 'Login attempts increased' );
600 is( $patron->account_locked, 1, 'Check locked status' );
602 # And another try to go over the limit: different return value!
603 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
604 is( @test, 0, 'checkpw failed again and returns nothing now' );
605 $patron->discard_changes; # refresh
606 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
608 # Administrative lockout cannot be undone?
609 # Pass the right password now (or: add a nice mock).
610 my $auth = Test::MockModule->new( 'C4::Auth' );
611 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
612 $patron->login_attempts(0)->store;
613 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
614 is( $test[0], 1, 'Build confidence in the mock' );
615 $patron->login_attempts(-1)->store;
616 is( $patron->account_locked, 1, 'Check administrative lockout' );
617 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
618 is( @test, 0, 'checkpw gave red' );
619 $patron->discard_changes; # refresh
620 is( $patron->login_attempts, -1, 'Still locked out' );
621 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
622 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
625 subtest 'Check value of login_attempts in checkpw' => sub {
628 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
629 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
630 $patron->set_password({ password => '123', skip_validation => 1 });
632 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
633 is( $test[0], 1, 'Patron authenticated correctly' );
635 $patron->password_expiration_date('2020-01-01')->store;
636 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
637 is( $test[0], -2, 'Patron returned as expired correctly' );
641 subtest '_timeout_syspref' => sub {
645 t::lib::Mocks::mock_preference('timeout', "100");
646 is( C4::Auth::_timeout_syspref, 100, );
648 t::lib::Mocks::mock_preference('timeout', "2d");
649 is( C4::Auth::_timeout_syspref, 2*86400, );
651 t::lib::Mocks::mock_preference('timeout', "2D");
652 is( C4::Auth::_timeout_syspref, 2*86400, );
654 t::lib::Mocks::mock_preference('timeout', "10h");
655 is( C4::Auth::_timeout_syspref, 10*3600, );
657 t::lib::Mocks::mock_preference('timeout', "10x");
659 { is( C4::Auth::_timeout_syspref, 600, ); }
660 "The value of the system preference 'timeout' is not correct, defaulting to 600",
661 'Bad values throw a warning and fallback to 600';
664 subtest 'check_cookie_auth' => sub {
667 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
669 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
671 # Mock a CGI object with real userid param
672 my $cgi = Test::MockObject->new();
677 if ( $var eq 'userid' ) { return $patron->userid; }
680 $cgi->mock('multi_param', sub {return q{}} );
681 $cgi->mock( 'cookie', sub { return; } );
682 $cgi->mock( 'request_method', sub { return 'POST' } );
684 $ENV{REMOTE_ADDR} = '127.0.0.1';
686 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
687 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
689 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
690 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
691 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
693 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
695 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
696 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
697 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
699 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
702 subtest 'checkauth & check_cookie_auth' => sub {
705 # flags = 4 => { catalogue => 1 }
706 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
707 my $password = set_weak_password($patron);
709 my $cgi_mock = Test::MockModule->new('CGI');
710 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
714 my $auth = Test::MockModule->new( 'C4::Auth' );
715 # Tests will fail if we hit safe_exit
716 $auth->mock( 'safe_exit', sub { return } );
718 my ( $userid, $cookie, $sessionID, $flags );
720 # checkauth will redirect and safe_exit if not authenticated and not authorized
723 open STDOUT, '>', \$stdout;
724 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
725 like( $stdout, qr{<title>\s*Log in to your account} );
726 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
731 my $first_sessionID = $sessionID;
733 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
734 # Not authenticated yet, the login form is displayed
736 ( $userid, $cookie, $sessionID, $flags, $template ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1}, 'intranet', undef, undef, { do_not_print => 1 } );
737 is( $template->{VARS}->{loginprompt}, 1, );
739 # Sending undefined fails obviously
740 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
741 is( $auth_status, 'failed' );
742 is( $session, undef );
744 # Simulating the login form submission
745 $cgi->param('userid', $patron->userid);
746 $cgi->param('password', $password);
749 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
750 is( $sessionID, $first_sessionID );
751 is( $userid, $patron->userid );
753 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
754 is( $auth_status, 'ok' );
755 is( $session->id, $first_sessionID );
758 $cgi->param('logout.x', 1);
759 $cgi->delete( 'userid', 'password' );
760 ( $userid, $cookie, $sessionID, $flags, $template ) =
761 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
763 is( $sessionID, undef );
764 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
765 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
766 is( $auth_status, "expired");
767 is( $session, undef );
770 # Trying to access without sessionID
772 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
773 is( $auth_status, 'failed' );
774 is( $session, undef );
776 # This will fail on permissions
777 undef $ENV{"HTTP_COOKIE"};
781 open STDOUT, '>', \$stdout;
782 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
785 is( $userid, undef );
786 is( $sessionID, undef );
792 $cgi->param('userid', $patron->userid);
793 $cgi->param('password', $password);
794 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
795 is( $userid, $patron->userid );
796 $first_sessionID = $sessionID;
798 # Patron does not have the borrowers permission
799 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
803 open STDOUT, '>', \$stdout;
804 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
807 is( $userid, undef );
808 is( $sessionID, undef );
810 # When calling check_cookie_auth, the session will be deleted
811 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
812 is( $auth_status, "failed" );
813 is( $session, undef );
814 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
815 is( $auth_status, 'expired', 'Session no longer exists' );
817 # NOTE: It is not what the UI is doing.
818 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
819 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
820 # It then return "ok", when the previous called got "failed"
822 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
823 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
824 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
825 is( $userid, $patron->userid );
826 isnt( $sessionID, undef, 'Check if we have a sessionID' );
827 isnt( $sessionID, $first_sessionID, 'New value expected' );
828 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
829 is( $auth_status, "ok" );
830 is( $session->id, $sessionID, 'Same session' );
831 # Two additional tests on userenv
832 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
833 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
837 subtest 'Userenv clearing in check_cookie_auth' => sub {
838 # Note: We did already test userenv for a logged-in user in previous subtest
841 t::lib::Mocks::mock_preference( 'timeout', 600 );
844 # Create a new anonymous session by passing a fake session ID
845 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
846 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
847 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
848 is( $auth_status, 'anon', 'Should be anonymous' );
849 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
850 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
851 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
853 # Make the session expire now, check_cookie_auth will delete it
854 $session->param('lasttime', time() - 1200 );
856 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
857 is( $auth_status, 'expired', 'Should be expired' );
858 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
860 # Show that we clear the userenv again: set up env and check deleted session
861 C4::Context->_new_userenv( $sessionID );
862 C4::Context->set_userenv; # empty
863 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
864 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
865 is( $auth_status, 'expired', 'Should be expired already' );
866 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
869 $schema->storage->txn_rollback;
871 subtest 'checkpw() return values tests' => sub {
875 subtest 'Internal check tests' => sub {
879 $schema->storage->txn_begin;
882 my $password_expired;
884 my $mock_patron = Test::MockModule->new('Koha::Patron');
885 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
886 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
888 # Only interested here in regular login
889 t::lib::Mocks::mock_config( 'useshibboleth', undef );
893 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
894 my $password = set_weak_password($patron);
896 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
897 my $unused_userid = $patron_to_delete->userid;
898 my $unused_cardnumber = $patron_to_delete->cardnumber;
899 $patron_to_delete->delete;
902 my @return = checkpw( $patron->userid, $password, undef, );
903 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
907 my @matchpoints = qw(userid cardnumber);
908 foreach my $matchpoint (@matchpoints) {
910 @return = checkpw( $patron->$matchpoint, $password, undef, );
912 is( $return[0], 1, "Password validation successful returns 1 ($matchpoint)" );
913 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
914 is( $return[2], $patron->userid, '`userid` returned' );
915 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
916 is( $return[3]->id, $patron->id, 'Correct patron returned' );
919 @return = checkpw( $patron->userid, $password . 'hey', undef, );
921 is( scalar @return, 2, "Two results on invalid password scenario" );
922 is( $return[0], 0, '0 returned on invalid password' );
923 is( ref( $return[1] ), 'Koha::Patron' );
924 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
926 $password_expired = 1;
927 @return = checkpw( $patron->userid, $password, undef, );
929 is( scalar @return, 2, "Two results on expired password scenario" );
930 is( $return[0], -2, '-2 returned' );
931 is( ref( $return[1] ), 'Koha::Patron' );
932 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
934 @return = checkpw( $unused_userid, $password, undef, );
936 is( scalar @return, 2, "Two results on non-existing userid scenario" );
937 is( $return[0], 0, '0 returned' );
938 is( $return[1], undef, 'Undef returned, representing no match' );
940 @return = checkpw( $unused_cardnumber, $password, undef, );
942 is( scalar @return, 2, "Only one result on non-existing cardnumber scenario" );
943 is( $return[0], 0, '0 returned' );
944 is( $return[1], undef, 'Undef returned, representing no match' );
946 $schema->storage->txn_rollback;
949 subtest 'CAS check (mocked) tests' => sub {
953 $schema->storage->txn_begin;
956 my $password_expired;
958 my $mock_patron = Test::MockModule->new('Koha::Patron');
959 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
960 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
962 # Only interested here in regular login
963 t::lib::Mocks::mock_config( 'useshibboleth', undef );
967 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
968 my $password = 'thePassword123';
969 $patron->set_password( { password => $password, skip_validation => 1 } );
971 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
972 my $unused_userid = $patron_to_delete->userid;
973 my $unused_cardnumber = $patron_to_delete->cardnumber;
974 $patron_to_delete->delete;
976 my $ticket = '123456';
977 my $query = CGI->new;
978 $query->param( -name => 'ticket', -value => $ticket );
980 my @cas_return = ( 1, $patron->cardnumber, $patron->userid, $ticket, Koha::Patrons->find( $patron->id ) );
982 my $cas_mock = Test::MockModule->new('C4::Auth');
983 $cas_mock->mock( 'checkpw_cas', sub { return @cas_return; } );
986 my @return = checkpw( $patron->userid, $password, $query, );
987 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
991 my @matchpoints = qw(userid cardnumber);
992 foreach my $matchpoint (@matchpoints) {
994 @return = checkpw( $patron->$matchpoint, $password, $query, );
996 is( $return[0], 1, "Password validation successful returns 1 ($matchpoint)" );
997 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
998 is( $return[2], $patron->userid, '`userid` returned' );
999 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
1000 is( $return[3]->id, $patron->id, 'Correct patron returned' );
1003 @return = checkpw( $patron->userid, $password . 'hey', $query, );
1005 is( scalar @return, 2, "Two results on invalid password scenario" );
1006 is( $return[0], 0, '0 returned on invalid password' );
1007 is( ref( $return[1] ), 'Koha::Patron' );
1008 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1010 $password_expired = 1;
1011 @return = checkpw( $patron->userid, $password, $query, );
1013 is( scalar @return, 2, "Two results on expired password scenario" );
1014 is( $return[0], -2, '-2 returned' );
1015 is( ref( $return[1] ), 'Koha::Patron' );
1016 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1018 @return = checkpw( $unused_userid, $password, $query, );
1020 is( scalar @return, 2, "Two results on non-existing userid scenario" );
1021 is( $return[0], 0, '0 returned' );
1022 is( $return[1], undef, 'Undef returned, representing no match' );
1024 @return = checkpw( $unused_cardnumber, $password, $query, );
1026 is( scalar @return, 2, "Only one result on non-existing cardnumber scenario" );
1027 is( $return[0], 0, '0 returned' );
1028 is( $return[1], undef, 'Undef returned, representing no match' );
1030 $schema->storage->txn_rollback;
1033 subtest 'Shibboleth check (mocked) tests' => sub {
1037 $schema->storage->txn_begin;
1040 my $password_expired;
1042 my $mock_patron = Test::MockModule->new('Koha::Patron');
1043 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
1044 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1046 # Only interested here in regular login
1047 t::lib::Mocks::mock_config( 'useshibboleth', 1 );
1049 $C4::Auth::ldap = 0;
1051 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1052 my $password = 'thePassword123';
1053 $patron->set_password( { password => $password, skip_validation => 1 } );
1055 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
1056 my $unused_userid = $patron_to_delete->userid;
1057 my $unused_cardnumber = $patron_to_delete->cardnumber;
1058 $patron_to_delete->delete;
1060 my @shib_return = ( 1, $patron->cardnumber, $patron->userid, Koha::Patrons->find( $patron->id ) );
1062 my $auth_mock = Test::MockModule->new('C4::Auth');
1063 $auth_mock->mock( 'shib_ok', 1 );
1064 $auth_mock->mock( 'get_login_shib', 1 );
1066 my $shib_mock = Test::MockModule->new('C4::Auth_with_shibboleth');
1067 $shib_mock->mock( 'checkpw_shib', sub { return @shib_return; } );
1069 $account_locked = 1;
1070 my @return = checkpw( $patron->userid );
1071 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1073 $account_locked = 0;
1075 @return = checkpw();
1077 is( $return[0], 1, "Password validation successful returns 1" );
1078 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
1079 is( $return[2], $patron->userid, '`userid` returned' );
1080 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
1081 is( $return[3]->id, $patron->id, 'Correct patron returned' );
1083 $schema->storage->txn_rollback;
1087 sub set_weak_password {
1089 my $password = 'password';
1090 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1091 $patron->set_password( { password => $password } );