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