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