Bug 30524: Unit tests
[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 => 19;
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(
24         'C4::Auth',
25         qw( checkauth haspermission track_login_daily checkpw get_template_and_user checkpw_hash get_cataloguing_page_permissions )
26     );
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( 'PrivacyPolicyConsent', '' ); # 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     ok(defined($template->{VARS}->{'csrf_token'}), "CSRF token returned");
606
607     delete $ENV{"HTTP_COOKIE"};
608 };
609
610 # Check that there is always an OPACBaseURL set.
611 my $input = CGI->new();
612 my ( $template1, $borrowernumber, $cookie );
613 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
614     {
615         template_name => "opac-detail.tt",
616         type => "opac",
617         query => $input,
618         authnotrequired => 1,
619     }
620 );
621
622 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
623     'OPACBaseURL is in OPAC template' );
624
625 my ( $template2 );
626 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
627     {
628         template_name => "catalogue/detail.tt",
629         type => "intranet",
630         query => $input,
631         authnotrequired => 1,
632     }
633 );
634
635 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
636     'OPACBaseURL is in Staff template' );
637
638 my $hash1 = hash_password('password');
639 my $hash2 = hash_password('password');
640
641 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
642 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
643
644 subtest 'Check value of login_attempts in checkpw' => sub {
645     plan tests => 11;
646
647     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
648
649     # Only interested here in regular login
650     $C4::Auth::cas  = 0;
651     $C4::Auth::ldap = 0;
652
653     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
654     $patron->login_attempts(2);
655     $patron->password('123')->store; # yes, deliberately not hashed
656
657     is( $patron->account_locked, 0, 'Patron not locked' );
658     my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
659         # Note: 123 will not be hashed to 123 !
660     is( $test[0], 0, 'checkpw should have failed' );
661     $patron->discard_changes; # refresh
662     is( $patron->login_attempts, 3, 'Login attempts increased' );
663     is( $patron->account_locked, 1, 'Check locked status' );
664
665     # And another try to go over the limit: different return value!
666     @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
667     is( @test, 0, 'checkpw failed again and returns nothing now' );
668     $patron->discard_changes; # refresh
669     is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
670
671     # Administrative lockout cannot be undone?
672     # Pass the right password now (or: add a nice mock).
673     my $auth = Test::MockModule->new( 'C4::Auth' );
674     $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
675     $patron->login_attempts(0)->store;
676     @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
677     is( $test[0], 1, 'Build confidence in the mock' );
678     $patron->login_attempts(-1)->store;
679     is( $patron->account_locked, 1, 'Check administrative lockout' );
680     @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
681     is( @test, 0, 'checkpw gave red' );
682     $patron->discard_changes; # refresh
683     is( $patron->login_attempts, -1, 'Still locked out' );
684     t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
685     is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
686 };
687
688 subtest 'Check value of login_attempts in checkpw' => sub {
689     plan tests => 2;
690
691     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
692     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
693     $patron->set_password({ password => '123', skip_validation => 1 });
694
695     my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
696     is( $test[0], 1, 'Patron authenticated correctly' );
697
698     $patron->password_expiration_date('2020-01-01')->store;
699     @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
700     is( $test[0], -2, 'Patron returned as expired correctly' );
701
702 };
703
704 subtest '_timeout_syspref' => sub {
705
706     plan tests => 6;
707
708     t::lib::Mocks::mock_preference('timeout', "100");
709     is( C4::Auth::_timeout_syspref, 100, );
710
711     t::lib::Mocks::mock_preference('timeout', "2d");
712     is( C4::Auth::_timeout_syspref, 2*86400, );
713
714     t::lib::Mocks::mock_preference('timeout', "2D");
715     is( C4::Auth::_timeout_syspref, 2*86400, );
716
717     t::lib::Mocks::mock_preference('timeout', "10h");
718     is( C4::Auth::_timeout_syspref, 10*3600, );
719
720     t::lib::Mocks::mock_preference('timeout', "10x");
721     warning_is
722         { is( C4::Auth::_timeout_syspref, 600, ); }
723         "The value of the system preference 'timeout' is not correct, defaulting to 600",
724         'Bad values throw a warning and fallback to 600';
725 };
726
727 subtest 'check_cookie_auth' => sub {
728     plan tests => 4;
729
730     t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
731
732     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
733
734     # Mock a CGI object with real userid param
735     my $cgi = Test::MockObject->new();
736     $cgi->mock(
737         'param',
738         sub {
739             my $var = shift;
740             if ( $var eq 'userid' ) { return $patron->userid; }
741         }
742     );
743     $cgi->mock('multi_param', sub {return q{}} );
744     $cgi->mock( 'cookie', sub { return; } );
745     $cgi->mock( 'request_method', sub { return 'POST' } );
746
747     $ENV{REMOTE_ADDR} = '127.0.0.1';
748
749     # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
750     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
751
752     my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
753     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
754     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
755
756     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
757
758     ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
759     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
760     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
761
762     #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
763 };
764
765 subtest 'checkauth & check_cookie_auth' => sub {
766     plan tests => 35;
767
768     # flags = 4 => { catalogue => 1 }
769     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
770     my $password = 'password';
771     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
772     $patron->set_password( { password => $password } );
773
774     my $cgi_mock = Test::MockModule->new('CGI');
775     $cgi_mock->mock( 'request_method', sub { return 'POST' } );
776
777     my $cgi = CGI->new;
778
779     my $auth = Test::MockModule->new( 'C4::Auth' );
780     # Tests will fail if we hit safe_exit
781     $auth->mock( 'safe_exit', sub { return } );
782
783     my ( $userid, $cookie, $sessionID, $flags );
784     {
785         # checkauth will redirect and safe_exit if not authenticated and not authorized
786         local *STDOUT;
787         my $stdout;
788         open STDOUT, '>', \$stdout;
789         C4::Auth::checkauth($cgi, 0, {catalogue => 1});
790         like( $stdout, qr{<title>\s*Log in to your account} );
791         $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
792         ok($sessionID);
793         close STDOUT;
794     };
795
796     my $first_sessionID = $sessionID;
797
798     $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
799     # Not authenticated yet, checkauth didn't return the session
800     {
801         local *STDOUT;
802         my $stdout;
803         open STDOUT, '>', \$stdout;
804         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
805         close STDOUT;
806     }
807     is( $sessionID, undef);
808     is( $userid, undef);
809
810     # Sending undefined fails obviously
811     my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
812     is( $auth_status, 'failed' );
813     is( $session, undef );
814
815     # Simulating the login form submission
816     $cgi->param('userid', $patron->userid);
817     $cgi->param('password', $password);
818
819     # Logged in!
820     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
821     is( $sessionID, $first_sessionID );
822     is( $userid, $patron->userid );
823
824     ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
825     is( $auth_status, 'ok' );
826     is( $session->id, $first_sessionID );
827
828     my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' });
829     my $fresh_userid = $patron_to_delete->userid;
830     $patron_to_delete->delete;
831     my $old_userid   = $patron->userid;
832
833     # change the current session user's userid
834     $patron->userid( $fresh_userid )->store;
835     ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
836     is( $auth_status, 'expired' );
837     is( $session, undef );
838
839     # restore userid and generate a new session
840     $patron->userid($old_userid)->store;
841     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
842     is( $sessionID, $first_sessionID );
843     is( $userid, $patron->userid );
844
845     # Logging out!
846     $cgi->param('logout.x', 1);
847     $cgi->delete( 'userid', 'password' );
848     {
849         local *STDOUT;
850         my $stdout;
851         open STDOUT, '>', \$stdout;
852         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
853         close STDOUT;
854     }
855     is( $sessionID, undef );
856     is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
857     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
858     is( $auth_status, "expired");
859     is( $session, undef );
860
861     {
862         # Trying to access without sessionID
863         $cgi = CGI->new;
864         ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
865         is( $auth_status, 'failed' );
866         is( $session, undef );
867
868         # This will fail on permissions
869         undef $ENV{"HTTP_COOKIE"};
870         {
871             local *STDOUT;
872             my $stdout;
873             open STDOUT, '>', \$stdout;
874             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
875             close STDOUT;
876         }
877         is( $userid, undef );
878         is( $sessionID, undef );
879     }
880
881     {
882         # First logging in
883         $cgi = CGI->new;
884         $cgi->param('userid', $patron->userid);
885         $cgi->param('password', $password);
886         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
887         is( $userid, $patron->userid );
888         $first_sessionID = $sessionID;
889
890         # Patron does not have the borrowers permission
891         # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
892         {
893             local *STDOUT;
894             my $stdout;
895             open STDOUT, '>', \$stdout;
896             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
897             close STDOUT;
898         }
899         is( $userid, undef );
900         is( $sessionID, undef );
901
902         # When calling check_cookie_auth, the session will be deleted
903         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
904         is( $auth_status, "failed" );
905         is( $session, undef );
906         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
907         is( $auth_status, 'expired', 'Session no longer exists' );
908
909         # NOTE: It is not what the UI is doing.
910         # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
911         # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
912         # It then return "ok", when the previous called got "failed"
913
914         # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
915         $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
916         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
917         is( $userid, $patron->userid );
918         isnt( $sessionID, undef, 'Check if we have a sessionID' );
919         isnt( $sessionID, $first_sessionID, 'New value expected' );
920         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
921         is( $auth_status, "ok" );
922         is( $session->id, $sessionID, 'Same session' );
923         # Two additional tests on userenv
924         is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
925         is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
926     }
927 };
928
929 subtest 'Userenv clearing in check_cookie_auth' => sub {
930     # Note: We did already test userenv for a logged-in user in previous subtest
931     plan tests => 9;
932
933     t::lib::Mocks::mock_preference( 'timeout', 600 );
934     my $cgi = CGI->new;
935
936     # Create a new anonymous session by passing a fake session ID
937     $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
938     my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
939     my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
940     is( $auth_status, 'anon', 'Should be anonymous' );
941     is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
942     is( defined C4::Context->userenv, 1, 'There should be a userenv' );
943     is(  C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
944
945     # Make the session expire now, check_cookie_auth will delete it
946     $session->param('lasttime', time() - 1200 );
947     $session->flush;
948     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
949     is( $auth_status, 'expired', 'Should be expired' );
950     is( C4::Context->userenv, undef, 'Environment should be cleared too' );
951
952     # Show that we clear the userenv again: set up env and check deleted session
953     C4::Context->_new_userenv( $sessionID );
954     C4::Context->set_userenv; # empty
955     is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
956     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
957     is( $auth_status, 'expired', 'Should be expired already' );
958     is( C4::Context->userenv, undef, 'Environment should be cleared again' );
959 };
960
961 subtest 'create_basic_session tests' => sub {
962     plan tests => 13;
963
964     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
965
966     my $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'opac' });
967
968     isnt($session->id, undef, 'A new sessionID was created');
969     is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' );
970     is( $session->param('id'), $patron->userid, 'Session parameter id matches' );
971     is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' );
972     is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' );
973     is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' );
974     is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' );
975     is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' );
976     is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' );
977     is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' );
978     is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' );
979     is( $session->param('interface'), 'opac', 'Session parameter interface matches' );
980
981     $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'staff' });
982     is( $session->param('interface'), 'intranet', 'Staff interface gets converted to intranet' );
983 };
984
985 subtest 'check_cookie_auth overwriting interface already set' => sub {
986     plan tests => 2;
987
988     t::lib::Mocks::mock_preference( 'SessionRestrictionByIP', 0 );
989
990     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
991     my $session = C4::Auth::get_session();
992     $session->param( 'number',       $patron->id );
993     $session->param( 'id',           $patron->userid );
994     $session->param( 'ip',           '1.2.3.4' );
995     $session->param( 'lasttime',     time() );
996     $session->param( 'interface',    'opac' );
997     $session->flush;
998
999     C4::Context->interface('intranet');
1000     C4::Auth::check_cookie_auth( $session->id );
1001     is( C4::Context->interface, 'intranet', 'check_cookie_auth did not overwrite' );
1002     delete $C4::Context::context->{interface}; # clear context interface
1003     C4::Auth::check_cookie_auth( $session->id );
1004     is( C4::Context->interface, 'opac', 'check_cookie_auth used interface from session when context interface was empty' );
1005
1006     t::lib::Mocks::mock_preference( 'SessionRestrictionByIP', 1 );
1007 };
1008
1009 $schema->storage->txn_rollback;
1010
1011 subtest 'get_cataloguing_page_permissions() tests' => sub {
1012
1013     plan tests => 6;
1014
1015     $schema->storage->txn_begin;
1016
1017     my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 2**2 } } );    # catalogue
1018
1019     ok(
1020         !C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1021         '"catalogue" is not enough to see the cataloguing page'
1022     );
1023
1024     $builder->build(
1025         {
1026             source => 'UserPermission',
1027             value  => {
1028                 borrowernumber => $patron->id,
1029                 module_bit     => 24,               # stockrotation
1030                 code           => 'manage_rotas',
1031             },
1032         }
1033     );
1034
1035     t::lib::Mocks::mock_preference( 'StockRotation', 1 );
1036     ok(
1037         C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1038         '"stockrotation => manage_rotas" is enough'
1039     );
1040
1041     t::lib::Mocks::mock_preference( 'StockRotation', 0 );
1042     ok(
1043         !C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1044         '"stockrotation => manage_rotas" is not enough when `StockRotation` is disabled'
1045     );
1046
1047     $builder->build(
1048         {
1049             source => 'UserPermission',
1050             value  => {
1051                 borrowernumber => $patron->id,
1052                 module_bit     => 13,                     # tools
1053                 code           => 'manage_staged_marc',
1054             },
1055         }
1056     );
1057
1058     ok(
1059         C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1060         'Having one of the listed `tools` subperm is enough'
1061     );
1062
1063     $schema->resultset('UserPermission')->search( { borrowernumber => $patron->id } )->delete;
1064
1065     ok(
1066         !C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1067         'Permission removed, no access'
1068     );
1069
1070     $builder->build(
1071         {
1072             source => 'UserPermission',
1073             value  => {
1074                 borrowernumber => $patron->id,
1075                 module_bit     => 9,                    # editcatalogue
1076                 code           => 'delete_all_items',
1077             },
1078         }
1079     );
1080
1081     ok(
1082         C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1083         'Having any `editcatalogue` subperm is enough'
1084     );
1085
1086     $schema->storage->txn_rollback;
1087 };