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