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