Bug 19532: (follow-up) aria-hidden attr on OPAC, and more
[koha.git] / t / db_dependent / Auth.t
1 #!/usr/bin/perl
2 #
3 # This Koha test module is a stub!  
4 # Add more tests here!!!
5
6 use Modern::Perl;
7
8 use CGI qw ( -utf8 );
9
10 use Test::MockObject;
11 use Test::MockModule;
12 use List::MoreUtils qw/all any none/;
13 use Test::More tests => 24;
14 use Test::Warn;
15 use t::lib::Mocks;
16 use t::lib::TestBuilder;
17
18 use C4::Members;
19 use Koha::AuthUtils qw/hash_password/;
20 use Koha::Database;
21 use Koha::Patrons;
22
23 BEGIN {
24     use_ok('C4::Auth', qw( checkauth haspermission track_login_daily checkpw get_template_and_user checkpw_hash ));
25 }
26
27 my $schema  = Koha::Database->schema;
28 my $builder = t::lib::TestBuilder->new;
29 my $dbh     = C4::Context->dbh;
30
31 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
32 # handling
33 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
34 t::lib::Mocks::mock_preference( 'GDPR_Policy', '' ); # Disabled
35
36 $schema->storage->txn_begin;
37
38 subtest 'checkauth() tests' => sub {
39
40     plan tests => 4;
41
42     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
43
44     # Mock a CGI object with real userid param
45     my $cgi = Test::MockObject->new();
46     $cgi->mock(
47         'param',
48         sub {
49             my $var = shift;
50             if ( $var eq 'userid' ) { return $patron->userid; }
51         }
52     );
53     $cgi->mock( 'cookie', sub { return; } );
54     $cgi->mock( 'request_method', sub { return 'POST' } );
55
56     my $authnotrequired = 1;
57     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
58
59     is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
60
61     my $db_user_id = C4::Context->config('user');
62     my $db_user_pass = C4::Context->config('pass');
63     $cgi = Test::MockObject->new();
64     $cgi->mock( 'cookie', sub { return; } );
65     $cgi->mock( 'param', sub {
66             my ( $self, $param ) = @_;
67             if ( $param eq 'userid' ) { return $db_user_id; }
68             elsif ( $param eq 'password' ) { return $db_user_pass; }
69             else { return; }
70         });
71     $cgi->mock( 'request_method', sub { return 'POST' } );
72     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
73     is ( $userid, undef, 'If DB user is used, it should not be logged in' );
74
75     my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
76
77     # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
78     ok( !$is_allowed, 'DB user should not have any permissions');
79
80     subtest 'Prevent authentication when sending credential via GET' => sub {
81
82         plan tests => 2;
83
84         my $patron = $builder->build_object(
85             { class => 'Koha::Patrons', value => { flags => 1 } } );
86         my $password = 'password';
87         t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
88         $patron->set_password( { password => $password } );
89         $cgi = Test::MockObject->new();
90         $cgi->mock( 'cookie', sub { return; } );
91         $cgi->mock(
92             'param',
93             sub {
94                 my ( $self, $param ) = @_;
95                 if    ( $param eq 'userid' )   { return $patron->userid; }
96                 elsif ( $param eq 'password' ) { return $password; }
97                 else                           { return; }
98             }
99         );
100
101         $cgi->mock( 'request_method', sub { return 'POST' } );
102         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
103         is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
104
105         $cgi->mock( 'request_method', sub { return 'GET' } );
106         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
107         is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
108     };
109
110     C4::Context->_new_userenv; # For next tests
111
112 };
113
114 subtest 'track_login_daily tests' => sub {
115
116     plan tests => 5;
117
118     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
119     my $userid = $patron->userid;
120
121     $patron->lastseen( undef );
122     $patron->store();
123
124     my $cache     = Koha::Caches->get_instance();
125     my $cache_key = "track_login_" . $patron->userid;
126     $cache->clear_from_cache($cache_key);
127
128     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
129
130     is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
131
132     C4::Auth::track_login_daily( $userid );
133     $patron->_result()->discard_changes();
134     isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
135
136     sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
137     my $last_seen = $patron->lastseen;
138     C4::Auth::track_login_daily( $userid );
139     $patron->_result()->discard_changes();
140     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
141
142     $cache->clear_from_cache($cache_key);
143     C4::Auth::track_login_daily( $userid );
144     $patron->_result()->discard_changes();
145     isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
146
147     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
148     $patron->lastseen( undef )->store;
149     $cache->clear_from_cache($cache_key);
150     C4::Auth::track_login_daily( $userid );
151     $patron->_result()->discard_changes();
152     is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
153
154 };
155
156 subtest 'no_set_userenv parameter tests' => sub {
157
158     plan tests => 7;
159
160     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
161     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
162     my $password = 'password';
163
164     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
165     $patron->set_password({ password => $password });
166
167     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
168     is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
169     C4::Context->_new_userenv('DUMMY SESSION');
170     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
171     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
172     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
173     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
174     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
175     isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
176 };
177
178 subtest 'checkpw lockout tests' => sub {
179
180     plan tests => 5;
181
182     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
183     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
184     my $password = 'password';
185     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
186     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
187     $patron->set_password({ password => $password });
188
189     my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
190     ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
191     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
192     is( $checkpw, 0, 'checkpw returns false when given wrong password' );
193     $patron = $patron->get_from_storage;
194     is( $patron->account_locked, 1, "Account is locked from failed login");
195     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
196     is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
197     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
198     is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
199
200 };
201
202 # get_template_and_user tests
203
204 {   # Tests for the language URL parameter
205
206     sub MockedCheckauth {
207         my ($query,$authnotrequired,$flagsrequired,$type) = @_;
208         # return vars
209         my $userid = 'cobain';
210         my $sessionID = 234;
211         # we don't need to bother about permissions for this test
212         my $flags = {
213             superlibrarian    => 1, acquisition       => 0,
214             borrowers         => 0,
215             catalogue         => 1, circulate         => 0,
216             coursereserves    => 0, editauthorities   => 0,
217             editcatalogue     => 0,
218             parameters        => 0, permissions       => 0,
219             plugins           => 0, reports           => 0,
220             reserveforothers  => 0, serials           => 0,
221             staffaccess       => 0, tools             => 0,
222             updatecharges     => 0
223         };
224
225         my $session_cookie = $query->cookie(
226             -name => 'CGISESSID',
227             -value    => 'nirvana',
228             -HttpOnly => 1
229         );
230
231         return ( $userid, $session_cookie, $sessionID, $flags );
232     }
233
234     # Mock checkauth, build the scenario
235     my $auth = Test::MockModule->new( 'C4::Auth' );
236     $auth->mock( 'checkauth', \&MockedCheckauth );
237
238     # Make sure 'EnableOpacSearchHistory' is set
239     t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
240     # Enable es-ES for the OPAC and staff interfaces
241     t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
242     t::lib::Mocks::mock_preference('language','en,es-ES');
243
244     # we need a session cookie
245     $ENV{"SERVER_PORT"} = 80;
246     $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
247
248     my $query = CGI->new;
249     $query->param('language','es-ES');
250
251     my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
252         {
253             template_name   => "about.tt",
254             query           => $query,
255             type            => "opac",
256             authnotrequired => 1,
257             flagsrequired   => { catalogue => 1 },
258             debug           => 1
259         }
260     );
261
262     ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
263             'BZ9735: the cookies array is flat' );
264
265     # new query, with non-existent language (we only have en and es-ES)
266     $query->param('language','tomas');
267
268     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
269         {
270             template_name   => "about.tt",
271             query           => $query,
272             type            => "opac",
273             authnotrequired => 1,
274             flagsrequired   => { catalogue => 1 },
275             debug           => 1
276         }
277     );
278
279     ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
280         'BZ9735: invalid language, it is not set');
281
282     ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
283         'BZ9735: invalid language, then default to en');
284
285     for my $template_name (
286         qw(
287             ../../../../../../../../../../../../../../../etc/passwd
288             test/../../../../../../../../../../../../../../etc/passwd
289             /etc/passwd
290             test/does_not_finished_by_tt_t
291         )
292     ) {
293         eval {
294             ( $template, $loggedinuser, $cookies ) = get_template_and_user(
295                 {
296                     template_name   => $template_name,
297                     query           => $query,
298                     type            => "intranet",
299                     authnotrequired => 1,
300                     flagsrequired   => { catalogue => 1 },
301                 }
302             );
303         };
304         like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
305     }
306     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
307         {
308             template_name   => 'errors/errorpage.tt',
309             query           => $query,
310             type            => "intranet",
311             authnotrequired => 1,
312             flagsrequired   => { catalogue => 1 },
313         }
314     );
315     my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
316     is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
317
318     # Regression test for env opac search limit override
319     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
320     $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
321
322     ( $template, $loggedinuser, $cookies) = get_template_and_user(
323         {
324             template_name => 'opac-main.tt',
325             query => $query,
326             type => 'opac',
327             authnotrequired => 1,
328         }
329     );
330     is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
331     is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
332
333     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
334
335     ( $template, $loggedinuser, $cookies) = get_template_and_user(
336         {
337             template_name => 'opac-main.tt',
338             query => $query,
339             type => 'opac',
340             authnotrequired => 1,
341         }
342     );
343     is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
344     is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
345 }
346
347 # Check that there is always an OPACBaseURL set.
348 my $input = CGI->new();
349 my ( $template1, $borrowernumber, $cookie );
350 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
351     {
352         template_name => "opac-detail.tt",
353         type => "opac",
354         query => $input,
355         authnotrequired => 1,
356     }
357 );
358
359 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
360     'OPACBaseURL is in OPAC template' );
361
362 my ( $template2 );
363 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
364     {
365         template_name => "catalogue/detail.tt",
366         type => "intranet",
367         query => $input,
368         authnotrequired => 1,
369     }
370 );
371
372 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
373     'OPACBaseURL is in Staff template' );
374
375 my $hash1 = hash_password('password');
376 my $hash2 = hash_password('password');
377
378 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
379 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
380
381 subtest 'Check value of login_attempts in checkpw' => sub {
382     plan tests => 11;
383
384     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
385
386     # Only interested here in regular login
387     $C4::Auth::cas  = 0;
388     $C4::Auth::ldap = 0;
389
390     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
391     $patron->login_attempts(2);
392     $patron->password('123')->store; # yes, deliberately not hashed
393
394     is( $patron->account_locked, 0, 'Patron not locked' );
395     my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
396         # Note: 123 will not be hashed to 123 !
397     is( $test[0], 0, 'checkpw should have failed' );
398     $patron->discard_changes; # refresh
399     is( $patron->login_attempts, 3, 'Login attempts increased' );
400     is( $patron->account_locked, 1, 'Check locked status' );
401
402     # And another try to go over the limit: different return value!
403     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
404     is( @test, 0, 'checkpw failed again and returns nothing now' );
405     $patron->discard_changes; # refresh
406     is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
407
408     # Administrative lockout cannot be undone?
409     # Pass the right password now (or: add a nice mock).
410     my $auth = Test::MockModule->new( 'C4::Auth' );
411     $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
412     $patron->login_attempts(0)->store;
413     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
414     is( $test[0], 1, 'Build confidence in the mock' );
415     $patron->login_attempts(-1)->store;
416     is( $patron->account_locked, 1, 'Check administrative lockout' );
417     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
418     is( @test, 0, 'checkpw gave red' );
419     $patron->discard_changes; # refresh
420     is( $patron->login_attempts, -1, 'Still locked out' );
421     t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
422     is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
423 };
424
425 subtest '_timeout_syspref' => sub {
426     plan tests => 5;
427
428     t::lib::Mocks::mock_preference('timeout', "100");
429     is( C4::Auth::_timeout_syspref, 100, );
430
431     t::lib::Mocks::mock_preference('timeout', "2d");
432     is( C4::Auth::_timeout_syspref, 2*86400, );
433
434     t::lib::Mocks::mock_preference('timeout', "2D");
435     is( C4::Auth::_timeout_syspref, 2*86400, );
436
437     t::lib::Mocks::mock_preference('timeout', "10h");
438     is( C4::Auth::_timeout_syspref, 10*3600, );
439
440     t::lib::Mocks::mock_preference('timeout', "10x");
441     is( C4::Auth::_timeout_syspref, 600, );
442 };
443
444 subtest 'check_cookie_auth' => sub {
445     plan tests => 4;
446
447     t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
448
449     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
450
451     # Mock a CGI object with real userid param
452     my $cgi = Test::MockObject->new();
453     $cgi->mock(
454         'param',
455         sub {
456             my $var = shift;
457             if ( $var eq 'userid' ) { return $patron->userid; }
458         }
459     );
460     $cgi->mock('multi_param', sub {return q{}} );
461     $cgi->mock( 'cookie', sub { return; } );
462     $cgi->mock( 'request_method', sub { return 'POST' } );
463
464     $ENV{REMOTE_ADDR} = '127.0.0.1';
465
466     # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
467     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
468
469     my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
470     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
471     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
472
473     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
474
475     ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
476     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
477     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
478
479     #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
480 };
481
482 $schema->storage->txn_rollback;