Bug 30524: Core CSRF checking code
[koha.git] / t / db_dependent / Auth.t
1 #!/usr/bin/perl
2 #
3 # This Koha test module is a stub!  
4 # Add more tests here!!!
5
6 use Modern::Perl;
7
8 use CGI qw ( -utf8 );
9
10 use Test::MockObject;
11 use Test::MockModule;
12 use List::MoreUtils qw/all any none/;
13 use Test::More tests => 16;
14 use Test::Warn;
15 use t::lib::Mocks;
16 use t::lib::TestBuilder;
17
18 use C4::Auth;
19 use C4::Members;
20 use Koha::AuthUtils qw/hash_password/;
21 use Koha::Database;
22 use Koha::Patrons;
23 use Koha::Auth::TwoFactorAuth;
24
25 BEGIN {
26     use_ok('C4::Auth', qw( checkauth haspermission track_login_daily checkpw get_template_and_user checkpw_hash ));
27 }
28
29 my $schema  = Koha::Database->schema;
30 my $builder = t::lib::TestBuilder->new;
31 my $dbh     = C4::Context->dbh;
32
33 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
34 # handling
35 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
36 t::lib::Mocks::mock_preference( 'GDPR_Policy', '' ); # Disabled
37
38 # To silence useless warnings
39 $ENV{REMOTE_ADDR} = '127.0.0.1';
40
41 $schema->storage->txn_begin;
42
43 subtest 'checkauth() tests' => sub {
44
45     plan tests => 7;
46
47     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
48
49     # Mock a CGI object with real userid param
50     my $cgi = Test::MockObject->new();
51     $cgi->mock(
52         'param',
53         sub {
54             my $var = shift;
55             if ( $var eq 'userid' ) { return $patron->userid; }
56         }
57     );
58     $cgi->mock( 'cookie', sub { return; } );
59     $cgi->mock( 'request_method', sub { return 'POST' } );
60
61     my $authnotrequired = 1;
62     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
63
64     is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
65
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; }
74             else { return; }
75         });
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' );
79
80     my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
81
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');
84
85     subtest 'Prevent authentication when sending credential via GET' => sub {
86
87         plan tests => 2;
88
89         my $patron = $builder->build_object(
90             { class => 'Koha::Patrons', value => { flags => 1 } } );
91         my $password = 'password';
92         t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
93         $patron->set_password( { password => $password } );
94         $cgi = Test::MockObject->new();
95         $cgi->mock( 'cookie', sub { return; } );
96         $cgi->mock(
97             'param',
98             sub {
99                 my ( $self, $param ) = @_;
100                 if    ( $param eq 'userid' )   { return $patron->userid; }
101                 elsif ( $param eq 'password' ) { return $password; }
102                 else                           { return; }
103             }
104         );
105
106         $cgi->mock( 'request_method', sub { return 'POST' } );
107         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
108         is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
109
110         $cgi->mock( 'request_method', sub { return 'GET' } );
111         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
112         is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
113     };
114
115     subtest 'Template params tests (password_expired)' => sub {
116
117         plan tests => 1;
118
119         my $password_expired;
120
121         my $patron_class = Test::MockModule->new('Koha::Patron');
122         $patron_class->mock( 'password_expired', sub { return $password_expired; } );
123
124         my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
125         my $password = 'password';
126         t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
127         $patron->set_password( { password => $password } );
128
129         my $cgi_mock = Test::MockModule->new('CGI')->mock( 'request_method', 'POST' );
130         my $cgi = CGI->new;
131         $cgi->param( -name => 'userid',   -value => $patron->userid );
132         $cgi->param( -name => 'password', -value => $password );
133
134         my $auth = Test::MockModule->new( 'C4::Auth' );
135         # Tests will fail if we hit safe_exit
136         $auth->mock( 'safe_exit', sub { return } );
137
138         my ( $userid, $cookie, $sessionID, $flags );
139
140         {
141             t::lib::Mocks::mock_preference( 'DumpTemplateVarsOpac', 1 );
142             # checkauth will redirect and safe_exit if not authenticated and not authorized
143             local *STDOUT;
144             my $stdout;
145             open STDOUT, '>', \$stdout;
146
147             # Password has expired
148             $password_expired = 1;
149             C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } );
150             like( $stdout, qr{'password_has_expired' => 1}, 'password_has_expired is set to 1' );
151
152             close STDOUT;
153         };
154     };
155
156     subtest 'While still logged in, relogin with another user' => sub {
157         plan tests => 6;
158
159         my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
160         my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
161         # Create 'former' session
162         my $session = C4::Auth::get_session();
163         $session->param( 'number',       $patron->id );
164         $session->param( 'id',           $patron->userid );
165         $session->param( 'ip',           '1.2.3.4' );
166         $session->param( 'lasttime',     time() );
167         $session->param( 'interface',    'opac' );
168         $session->flush;
169         my $sessionID = $session->id;
170         C4::Context->_new_userenv($sessionID);
171
172         my ( $return ) = C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
173         is( $return, 'ok', 'Former session in shape now' );
174
175         my $mock1 = Test::MockModule->new('C4::Auth');
176         $mock1->mock( 'safe_exit', sub {} );
177         my $mock2 = Test::MockModule->new('CGI');
178         $mock2->mock( 'request_method', 'POST' );
179         $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
180         my $cgi = CGI->new;
181         my $password = 'Incr3d1blyZtr@ng93$';
182         $patron2->set_password({ password => $password });
183         $cgi->param( -name => 'userid',             -value => $patron2->userid );
184         $cgi->param( -name => 'password',           -value => $password );
185         $cgi->param( -name => 'koha_login_context', -value => 1 );
186         my ( @return, $stdout );
187         {
188             local *STDOUT;
189             local %ENV;
190             $ENV{REMOTE_ADDR} = '1.2.3.4';
191             open STDOUT, '>', \$stdout;
192             @return = C4::Auth::checkauth( $cgi, 0, {} );
193             close STDOUT;
194         }
195         # Note: We can test return values from checkauth here since we mocked the safe_exit after the Redirect 303
196         is( $return[0], $patron2->userid, 'Login of patron2 approved' );
197         isnt( $return[2], $sessionID, 'Did not return previous session ID' );
198         ok( $return[2], 'New session ID not empty' );
199
200         # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
201         $patron2->flags(undef)->store;
202         $session->param( 'number',       $patron->id );
203         $session->param( 'id',           $patron->userid );
204         $session->param( 'interface',    'intranet' );
205         $session->flush;
206         $sessionID = $session->id;
207         C4::Context->_new_userenv($sessionID);
208         $cgi->param( -name => 'userid',             -value => $patron2->userid );
209         $cgi->param( -name => 'password',           -value => $password );
210         $cgi->param( -name => 'koha_login_context', -value => 1 );
211         {
212             local *STDOUT;
213             local %ENV;
214             $ENV{REMOTE_ADDR} = '1.2.3.4';
215             $stdout = q{};
216             open STDOUT, '>', \$stdout;
217             @return = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' ); # patron2 has no catalogue perm
218             close STDOUT;
219         }
220         like( $stdout, qr/You do not have permission to access this page/, 'No permission response' );
221         is( @return, 0, 'checkauth returned failure' );
222     };
223
224     subtest 'Two-factor authentication' => sub {
225
226         my $patron = $builder->build_object(
227             { class => 'Koha::Patrons', value => { flags => 1 } } );
228         my $password = 'password';
229         $patron->set_password( { password => $password } );
230         $cgi = Test::MockObject->new();
231
232         my $otp_token;
233         our ( $logout, $sessionID, $verified );
234         $cgi->mock(
235             'param',
236             sub {
237                 my ( $self, $param ) = @_;
238                 if    ( $param eq 'userid' )    { return $patron->userid; }
239                 elsif ( $param eq 'password' )  { return $password; }
240                 elsif ( $param eq 'otp_token' ) { return $otp_token; }
241                 elsif ( $param eq 'logout.x' )  { return $logout; }
242                 else                            { return; }
243             }
244         );
245         $cgi->mock( 'request_method', sub { return 'POST' } );
246         $cgi->mock( 'cookie', sub { return $sessionID } );
247
248         my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
249         $two_factor_auth->mock( 'verify', sub {$verified} );
250
251         my ( $userid, $cookie, $flags );
252         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
253
254         sub logout {
255             my $cgi = shift;
256             $logout = 1;
257             undef $sessionID;
258             C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
259             $logout = 0;
260         }
261
262         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
263         $patron->auth_method('password')->store;
264         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
265         is( $userid, $patron->userid, 'Succesful login' );
266         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
267         logout($cgi);
268
269         $patron->auth_method('two-factor')->store;
270         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
271         is( $userid, $patron->userid, 'Succesful login' );
272         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
273         logout($cgi);
274
275         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 1 );
276         t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
277         $patron->auth_method('password')->store;
278         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
279         is( $userid, $patron->userid, 'Succesful login' );
280         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
281         logout($cgi);
282
283         $patron->encode_secret('one_secret');
284         $patron->auth_method('two-factor');
285         $patron->store;
286         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
287         is( $userid, $patron->userid, 'Succesful login' );
288         my $session = C4::Auth::get_session($sessionID);
289         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
290
291         # Wrong OTP token
292         $otp_token = "wrong";
293         $verified = 0;
294         $patron->auth_method('two-factor')->store;
295         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
296         is( $userid, $patron->userid, 'Succesful login' );
297         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
298
299         $otp_token = "good";
300         $verified = 1;
301         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
302         is( $userid, $patron->userid, 'Succesful login' );
303         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
304
305         logout($cgi);
306         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
307         is( $userid, $patron->userid, 'Succesful login at the OPAC' );
308         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
309
310         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
311     };
312
313     C4::Context->_new_userenv; # For next tests
314
315 };
316
317 subtest 'track_login_daily tests' => sub {
318
319     plan tests => 5;
320
321     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
322     my $userid = $patron->userid;
323
324     $patron->lastseen( undef );
325     $patron->store();
326
327     my $cache     = Koha::Caches->get_instance();
328     my $cache_key = "track_login_" . $patron->userid;
329     $cache->clear_from_cache($cache_key);
330
331     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
332
333     is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
334
335     C4::Auth::track_login_daily( $userid );
336     $patron->_result()->discard_changes();
337     isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
338
339     sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
340     my $last_seen = $patron->lastseen;
341     C4::Auth::track_login_daily( $userid );
342     $patron->_result()->discard_changes();
343     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
344
345     $cache->clear_from_cache($cache_key);
346     C4::Auth::track_login_daily( $userid );
347     $patron->_result()->discard_changes();
348     isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
349
350     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
351     $patron->lastseen( undef )->store;
352     $cache->clear_from_cache($cache_key);
353     C4::Auth::track_login_daily( $userid );
354     $patron->_result()->discard_changes();
355     is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
356
357 };
358
359 subtest 'no_set_userenv parameter tests' => sub {
360
361     plan tests => 7;
362
363     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
364     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
365     my $password = 'password';
366
367     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
368     $patron->set_password({ password => $password });
369
370     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
371     is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
372     C4::Context->_new_userenv('DUMMY SESSION');
373     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
374     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
375     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
376     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
377     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
378     isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
379 };
380
381 subtest 'checkpw lockout tests' => sub {
382
383     plan tests => 5;
384
385     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
386     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
387     my $password = 'password';
388     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
389     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
390     $patron->set_password({ password => $password });
391
392     my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
393     ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
394     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
395     is( $checkpw, 0, 'checkpw returns false when given wrong password' );
396     $patron = $patron->get_from_storage;
397     is( $patron->account_locked, 1, "Account is locked from failed login");
398     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
399     is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
400     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
401     is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
402
403 };
404
405 # get_template_and_user tests
406
407 subtest 'get_template_and_user' => sub {   # Tests for the language URL parameter
408
409     sub MockedCheckauth {
410         my ($query,$authnotrequired,$flagsrequired,$type) = @_;
411         # return vars
412         my $userid = 'cobain';
413         my $sessionID = 234;
414         # we don't need to bother about permissions for this test
415         my $flags = {
416             superlibrarian    => 1, acquisition       => 0,
417             borrowers         => 0,
418             catalogue         => 1, circulate         => 0,
419             coursereserves    => 0, editauthorities   => 0,
420             editcatalogue     => 0,
421             parameters        => 0, permissions       => 0,
422             plugins           => 0, reports           => 0,
423             reserveforothers  => 0, serials           => 0,
424             staffaccess       => 0, tools             => 0,
425             updatecharges     => 0
426         };
427
428         my $session_cookie = $query->cookie(
429             -name => 'CGISESSID',
430             -value    => 'nirvana',
431             -HttpOnly => 1
432         );
433
434         return ( $userid, [ $session_cookie ], $sessionID, $flags );
435     }
436
437     # Mock checkauth, build the scenario
438     my $auth = Test::MockModule->new( 'C4::Auth' );
439     $auth->mock( 'checkauth', \&MockedCheckauth );
440
441     # Make sure 'EnableOpacSearchHistory' is set
442     t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
443     # Enable es-ES for the OPAC and staff interfaces
444     t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
445     t::lib::Mocks::mock_preference('language','en,es-ES');
446
447     # we need a session cookie
448     $ENV{"SERVER_PORT"} = 80;
449     $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
450
451     my $query = CGI->new;
452     $query->param('language','es-ES');
453
454     my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
455         {
456             template_name   => "about.tt",
457             query           => $query,
458             type            => "opac",
459             authnotrequired => 1,
460             flagsrequired   => { catalogue => 1 },
461             debug           => 1
462         }
463     );
464
465     ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
466             'BZ9735: the cookies array is flat' );
467
468     # new query, with non-existent language (we only have en and es-ES)
469     $query->param('language','tomas');
470
471     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
472         {
473             template_name   => "about.tt",
474             query           => $query,
475             type            => "opac",
476             authnotrequired => 1,
477             flagsrequired   => { catalogue => 1 },
478             debug           => 1
479         }
480     );
481
482     ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
483         'BZ9735: invalid language, it is not set');
484
485     ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
486         'BZ9735: invalid language, then default to en');
487
488     for my $template_name (
489         qw(
490             ../../../../../../../../../../../../../../../etc/passwd
491             test/../../../../../../../../../../../../../../etc/passwd
492             /etc/passwd
493             test/does_not_finished_by_tt_t
494         )
495     ) {
496         eval {
497             ( $template, $loggedinuser, $cookies ) = get_template_and_user(
498                 {
499                     template_name   => $template_name,
500                     query           => $query,
501                     type            => "intranet",
502                     authnotrequired => 1,
503                     flagsrequired   => { catalogue => 1 },
504                 }
505             );
506         };
507         like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
508     }
509     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
510         {
511             template_name   => 'errors/errorpage.tt',
512             query           => $query,
513             type            => "intranet",
514             authnotrequired => 1,
515             flagsrequired   => { catalogue => 1 },
516         }
517     );
518     my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
519     is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
520
521     # Regression test for env opac search limit override
522     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
523     $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
524
525     ( $template, $loggedinuser, $cookies) = get_template_and_user(
526         {
527             template_name => 'opac-main.tt',
528             query => $query,
529             type => 'opac',
530             authnotrequired => 1,
531         }
532     );
533     is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
534     is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
535
536     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
537
538     ( $template, $loggedinuser, $cookies) = get_template_and_user(
539         {
540             template_name => 'opac-main.tt',
541             query => $query,
542             type => 'opac',
543             authnotrequired => 1,
544         }
545     );
546     is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
547     is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
548     ok(defined($template->{VARS}->{'csrf_token'}), "CSRF token returned");
549
550     delete $ENV{"HTTP_COOKIE"};
551 };
552
553 # Check that there is always an OPACBaseURL set.
554 my $input = CGI->new();
555 my ( $template1, $borrowernumber, $cookie );
556 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
557     {
558         template_name => "opac-detail.tt",
559         type => "opac",
560         query => $input,
561         authnotrequired => 1,
562     }
563 );
564
565 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
566     'OPACBaseURL is in OPAC template' );
567
568 my ( $template2 );
569 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
570     {
571         template_name => "catalogue/detail.tt",
572         type => "intranet",
573         query => $input,
574         authnotrequired => 1,
575     }
576 );
577
578 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
579     'OPACBaseURL is in Staff template' );
580
581 my $hash1 = hash_password('password');
582 my $hash2 = hash_password('password');
583
584 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
585 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
586
587 subtest 'Check value of login_attempts in checkpw' => sub {
588     plan tests => 11;
589
590     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
591
592     # Only interested here in regular login
593     $C4::Auth::cas  = 0;
594     $C4::Auth::ldap = 0;
595
596     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
597     $patron->login_attempts(2);
598     $patron->password('123')->store; # yes, deliberately not hashed
599
600     is( $patron->account_locked, 0, 'Patron not locked' );
601     my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
602         # Note: 123 will not be hashed to 123 !
603     is( $test[0], 0, 'checkpw should have failed' );
604     $patron->discard_changes; # refresh
605     is( $patron->login_attempts, 3, 'Login attempts increased' );
606     is( $patron->account_locked, 1, 'Check locked status' );
607
608     # And another try to go over the limit: different return value!
609     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
610     is( @test, 0, 'checkpw failed again and returns nothing now' );
611     $patron->discard_changes; # refresh
612     is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
613
614     # Administrative lockout cannot be undone?
615     # Pass the right password now (or: add a nice mock).
616     my $auth = Test::MockModule->new( 'C4::Auth' );
617     $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
618     $patron->login_attempts(0)->store;
619     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
620     is( $test[0], 1, 'Build confidence in the mock' );
621     $patron->login_attempts(-1)->store;
622     is( $patron->account_locked, 1, 'Check administrative lockout' );
623     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
624     is( @test, 0, 'checkpw gave red' );
625     $patron->discard_changes; # refresh
626     is( $patron->login_attempts, -1, 'Still locked out' );
627     t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
628     is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
629 };
630
631 subtest 'Check value of login_attempts in checkpw' => sub {
632     plan tests => 2;
633
634     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
635     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
636     $patron->set_password({ password => '123', skip_validation => 1 });
637
638     my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
639     is( $test[0], 1, 'Patron authenticated correctly' );
640
641     $patron->password_expiration_date('2020-01-01')->store;
642     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
643     is( $test[0], -2, 'Patron returned as expired correctly' );
644
645 };
646
647 subtest '_timeout_syspref' => sub {
648
649     plan tests => 6;
650
651     t::lib::Mocks::mock_preference('timeout', "100");
652     is( C4::Auth::_timeout_syspref, 100, );
653
654     t::lib::Mocks::mock_preference('timeout', "2d");
655     is( C4::Auth::_timeout_syspref, 2*86400, );
656
657     t::lib::Mocks::mock_preference('timeout', "2D");
658     is( C4::Auth::_timeout_syspref, 2*86400, );
659
660     t::lib::Mocks::mock_preference('timeout', "10h");
661     is( C4::Auth::_timeout_syspref, 10*3600, );
662
663     t::lib::Mocks::mock_preference('timeout', "10x");
664     warning_is
665         { is( C4::Auth::_timeout_syspref, 600, ); }
666         "The value of the system preference 'timeout' is not correct, defaulting to 600",
667         'Bad values throw a warning and fallback to 600';
668 };
669
670 subtest 'check_cookie_auth' => sub {
671     plan tests => 4;
672
673     t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
674
675     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
676
677     # Mock a CGI object with real userid param
678     my $cgi = Test::MockObject->new();
679     $cgi->mock(
680         'param',
681         sub {
682             my $var = shift;
683             if ( $var eq 'userid' ) { return $patron->userid; }
684         }
685     );
686     $cgi->mock('multi_param', sub {return q{}} );
687     $cgi->mock( 'cookie', sub { return; } );
688     $cgi->mock( 'request_method', sub { return 'POST' } );
689
690     $ENV{REMOTE_ADDR} = '127.0.0.1';
691
692     # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
693     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
694
695     my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
696     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
697     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
698
699     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
700
701     ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
702     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
703     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
704
705     #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
706 };
707
708 subtest 'checkauth & check_cookie_auth' => sub {
709     plan tests => 31;
710
711     # flags = 4 => { catalogue => 1 }
712     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
713     my $password = 'password';
714     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
715     $patron->set_password( { password => $password } );
716
717     my $cgi_mock = Test::MockModule->new('CGI');
718     $cgi_mock->mock( 'request_method', sub { return 'POST' } );
719
720     my $cgi = CGI->new;
721
722     my $auth = Test::MockModule->new( 'C4::Auth' );
723     # Tests will fail if we hit safe_exit
724     $auth->mock( 'safe_exit', sub { return } );
725
726     my ( $userid, $cookie, $sessionID, $flags );
727     {
728         # checkauth will redirect and safe_exit if not authenticated and not authorized
729         local *STDOUT;
730         my $stdout;
731         open STDOUT, '>', \$stdout;
732         C4::Auth::checkauth($cgi, 0, {catalogue => 1});
733         like( $stdout, qr{<title>\s*Log in to your account} );
734         $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
735         ok($sessionID);
736         close STDOUT;
737     };
738
739     my $first_sessionID = $sessionID;
740
741     $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
742     # Not authenticated yet, checkauth didn't return the session
743     {
744         local *STDOUT;
745         my $stdout;
746         open STDOUT, '>', \$stdout;
747         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
748         close STDOUT;
749     }
750     is( $sessionID, undef);
751     is( $userid, undef);
752
753     # Sending undefined fails obviously
754     my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
755     is( $auth_status, 'failed' );
756     is( $session, undef );
757
758     # Simulating the login form submission
759     $cgi->param('userid', $patron->userid);
760     $cgi->param('password', $password);
761
762     # Logged in!
763     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
764     is( $sessionID, $first_sessionID );
765     is( $userid, $patron->userid );
766
767     ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
768     is( $auth_status, 'ok' );
769     is( $session->id, $first_sessionID );
770
771     # Logging out!
772     $cgi->param('logout.x', 1);
773     $cgi->delete( 'userid', 'password' );
774     {
775         local *STDOUT;
776         my $stdout;
777         open STDOUT, '>', \$stdout;
778         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
779         close STDOUT;
780     }
781     is( $sessionID, undef );
782     is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
783     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
784     is( $auth_status, "expired");
785     is( $session, undef );
786
787     {
788         # Trying to access without sessionID
789         $cgi = CGI->new;
790         ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
791         is( $auth_status, 'failed' );
792         is( $session, undef );
793
794         # This will fail on permissions
795         undef $ENV{"HTTP_COOKIE"};
796         {
797             local *STDOUT;
798             my $stdout;
799             open STDOUT, '>', \$stdout;
800             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
801             close STDOUT;
802         }
803         is( $userid, undef );
804         is( $sessionID, undef );
805     }
806
807     {
808         # First logging in
809         $cgi = CGI->new;
810         $cgi->param('userid', $patron->userid);
811         $cgi->param('password', $password);
812         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
813         is( $userid, $patron->userid );
814         $first_sessionID = $sessionID;
815
816         # Patron does not have the borrowers permission
817         # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
818         {
819             local *STDOUT;
820             my $stdout;
821             open STDOUT, '>', \$stdout;
822             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
823             close STDOUT;
824         }
825         is( $userid, undef );
826         is( $sessionID, undef );
827
828         # When calling check_cookie_auth, the session will be deleted
829         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
830         is( $auth_status, "failed" );
831         is( $session, undef );
832         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
833         is( $auth_status, 'expired', 'Session no longer exists' );
834
835         # NOTE: It is not what the UI is doing.
836         # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
837         # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
838         # It then return "ok", when the previous called got "failed"
839
840         # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
841         $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
842         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
843         is( $userid, $patron->userid );
844         isnt( $sessionID, undef, 'Check if we have a sessionID' );
845         isnt( $sessionID, $first_sessionID, 'New value expected' );
846         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
847         is( $auth_status, "ok" );
848         is( $session->id, $sessionID, 'Same session' );
849         # Two additional tests on userenv
850         is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
851         is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
852     }
853 };
854
855 subtest 'Userenv clearing in check_cookie_auth' => sub {
856     # Note: We did already test userenv for a logged-in user in previous subtest
857     plan tests => 9;
858
859     t::lib::Mocks::mock_preference( 'timeout', 600 );
860     my $cgi = CGI->new;
861
862     # Create a new anonymous session by passing a fake session ID
863     $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
864     my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
865     my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
866     is( $auth_status, 'anon', 'Should be anonymous' );
867     is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
868     is( defined C4::Context->userenv, 1, 'There should be a userenv' );
869     is(  C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
870
871     # Make the session expire now, check_cookie_auth will delete it
872     $session->param('lasttime', time() - 1200 );
873     $session->flush;
874     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
875     is( $auth_status, 'expired', 'Should be expired' );
876     is( C4::Context->userenv, undef, 'Environment should be cleared too' );
877
878     # Show that we clear the userenv again: set up env and check deleted session
879     C4::Context->_new_userenv( $sessionID );
880     C4::Context->set_userenv; # empty
881     is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
882     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
883     is( $auth_status, 'expired', 'Should be expired already' );
884     is( C4::Context->userenv, undef, 'Environment should be cleared again' );
885 };
886
887 $schema->storage->txn_rollback;