Bug 20489: Prevent DB user login
[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 => 21;
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
36 $schema->storage->txn_begin;
37
38 subtest 'checkauth() tests' => sub {
39
40     plan tests => 2;
41
42     my $patron = $builder->build({ source => 'Borrower', value => { flags => undef } })->{userid};
43
44     # Mock a CGI object with real userid param
45     my $cgi = Test::MockObject->new();
46     $cgi->mock( 'param', sub { return $patron; } );
47     $cgi->mock( 'cookie', sub { return; } );
48
49     my $authnotrequired = 1;
50     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
51
52     is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
53
54     my $db_user_id = C4::Context->config('user');
55     my $db_user_pass = C4::Context->config('pass');
56     $cgi = Test::MockObject->new();
57     $cgi->mock( 'cookie', sub { return; } );
58     $cgi->mock( 'param', sub {
59             my ( $self, $param ) = @_;
60             if ( $param eq 'userid' ) { return $db_user_id; }
61             elsif ( $param eq 'password' ) { return $db_user_pass; }
62             else { return; }
63         });
64     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
65     is ( $userid, undef, 'If DB user is used, it should not be logged in' );
66     C4::Context->_new_userenv; # For next tests
67
68 };
69
70 my $hash1 = hash_password('password');
71 my $hash2 = hash_password('password');
72
73 { # tests no_set_userenv parameter
74     my $patron = $builder->build( { source => 'Borrower' } );
75     Koha::Patrons->find( $patron->{borrowernumber} )->update_password( $patron->{userid}, $hash1 );
76     my $library = $builder->build(
77         {
78             source => 'Branch',
79         }
80     );
81
82     ok( checkpw( $dbh, $patron->{userid}, 'password', undef, undef, 1 ), 'checkpw returns true' );
83     is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
84     C4::Context->_new_userenv('DUMMY SESSION');
85     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, 'Library 1', 0, '', '');
86     is( C4::Context->userenv->{branch}, $library->{branchcode}, 'Userenv gives correct branch' );
87     ok( checkpw( $dbh, $patron->{userid}, 'password', undef, undef, 1 ), 'checkpw returns true' );
88     is( C4::Context->userenv->{branch}, $library->{branchcode}, 'Userenv branch is preserved if no_set_userenv is true' );
89     ok( checkpw( $dbh, $patron->{userid}, 'password', undef, undef, 0 ), 'checkpw still returns true' );
90     isnt( C4::Context->userenv->{branch}, $library->{branchcode}, 'Userenv branch is overwritten if no_set_userenv is false' );
91 }
92
93 # get_template_and_user tests
94
95 {   # Tests for the language URL parameter
96
97     sub MockedCheckauth {
98         my ($query,$authnotrequired,$flagsrequired,$type) = @_;
99         # return vars
100         my $userid = 'cobain';
101         my $sessionID = 234;
102         # we don't need to bother about permissions for this test
103         my $flags = {
104             superlibrarian    => 1, acquisition       => 0,
105             borrowers         => 0,
106             catalogue         => 1, circulate         => 0,
107             coursereserves    => 0, editauthorities   => 0,
108             editcatalogue     => 0, management        => 0,
109             parameters        => 0, permissions       => 0,
110             plugins           => 0, reports           => 0,
111             reserveforothers  => 0, serials           => 0,
112             staffaccess       => 0, tools             => 0,
113             updatecharges     => 0
114         };
115
116         my $session_cookie = $query->cookie(
117             -name => 'CGISESSID',
118             -value    => 'nirvana',
119             -HttpOnly => 1
120         );
121
122         return ( $userid, $session_cookie, $sessionID, $flags );
123     }
124
125     # Mock checkauth, build the scenario
126     my $auth = new Test::MockModule( 'C4::Auth' );
127     $auth->mock( 'checkauth', \&MockedCheckauth );
128
129     # Make sure 'EnableOpacSearchHistory' is set
130     t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
131     # Enable es-ES for the OPAC and staff interfaces
132     t::lib::Mocks::mock_preference('opaclanguages','en,es-ES');
133     t::lib::Mocks::mock_preference('language','en,es-ES');
134
135     # we need a session cookie
136     $ENV{"SERVER_PORT"} = 80;
137     $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
138
139     my $query = new CGI;
140     $query->param('language','es-ES');
141
142     my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
143         {
144             template_name   => "about.tt",
145             query           => $query,
146             type            => "opac",
147             authnotrequired => 1,
148             flagsrequired   => { catalogue => 1 },
149             debug           => 1
150         }
151     );
152
153     ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
154             'BZ9735: the cookies array is flat' );
155
156     # new query, with non-existent language (we only have en and es-ES)
157     $query->param('language','tomas');
158
159     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
160         {
161             template_name   => "about.tt",
162             query           => $query,
163             type            => "opac",
164             authnotrequired => 1,
165             flagsrequired   => { catalogue => 1 },
166             debug           => 1
167         }
168     );
169
170     ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
171         'BZ9735: invalid language, it is not set');
172
173     ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
174         'BZ9735: invalid language, then default to en');
175
176     for my $template_name (
177         qw(
178             ../../../../../../../../../../../../../../../etc/passwd
179             test/../../../../../../../../../../../../../../etc/passwd
180             /etc/passwd
181             test/does_not_finished_by_tt_t
182         )
183     ) {
184         eval {
185             ( $template, $loggedinuser, $cookies ) = get_template_and_user(
186                 {
187                     template_name   => $template_name,
188                     query           => $query,
189                     type            => "intranet",
190                     authnotrequired => 1,
191                     flagsrequired   => { catalogue => 1 },
192                 }
193             );
194         };
195         like ( $@, qr(^bad template path), "The file $template_name should not be accessible" );
196     }
197     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
198         {
199             template_name   => 'errors/errorpage.tt',
200             query           => $query,
201             type            => "intranet",
202             authnotrequired => 1,
203             flagsrequired   => { catalogue => 1 },
204         }
205     );
206     my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
207     is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
208 }
209
210 # Check that there is always an OPACBaseURL set.
211 my $input = CGI->new();
212 my ( $template1, $borrowernumber, $cookie );
213 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
214     {
215         template_name => "opac-detail.tt",
216         type => "opac",
217         query => $input,
218         authnotrequired => 1,
219     }
220 );
221
222 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
223     'OPACBaseURL is in OPAC template' );
224
225 my ( $template2 );
226 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
227     {
228         template_name => "catalogue/detail.tt",
229         type => "intranet",
230         query => $input,
231         authnotrequired => 1,
232     }
233 );
234
235 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
236     'OPACBaseURL is in Staff template' );
237
238 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
239 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');