Bug 14144: Silence warnings t/db_dependent/Auth_with_ldap.t
[koha.git] / t / db_dependent / Auth_with_ldap.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 4;
21 use Test::MockModule;
22 use Test::MockObject;
23 use t::lib::TestBuilder;
24 use Test::Warn;
25
26 use C4::Context;
27
28 my $dbh = C4::Context->dbh;
29 # Start transaction
30 $dbh->{ AutoCommit } = 0;
31 $dbh->{ RaiseError } = 1;
32
33 my $builder = t::lib::TestBuilder->new();
34
35 # Variables controlling LDAP server config
36 my $update         = 0;
37 my $replicate      = 0;
38 my $auth_by_bind   = 1;
39 my $anonymous_bind = 1;
40 # Variables controlling LDAP behaviour
41 my $desired_authentication_result = 'success';
42 my $desired_connection_result     = 'error';
43 my $desired_bind_result           = 'error';
44 my $desired_compare_result        = 'error';
45 my $desired_search_result         = 'error';
46 my $desired_count_result          = 1;
47 my $non_anonymous_bind_result     = 'error';
48 my $ret;
49
50 # Mock the context module
51 my $context     = new Test::MockModule( 'C4::Context' );
52 $context->mock( 'config', \&mockedC4Config );
53
54 # Mock the Net::LDAP module
55 my $ldap = new Test::MockModule( 'Net::LDAP' );
56
57 $ldap->mock( 'new',  sub {
58     if ( $desired_connection_result eq 'error' ) {
59         # We were asked to fail the LDAP conexion
60         return;
61     } else {
62         # Return a mocked Net::LDAP object (Test::MockObject)
63         return mock_net_ldap();
64     }
65 });
66
67 my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
68 my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode };
69 my $attrType = $builder->build({
70     source => 'BorrowerAttributeType',
71     value => {
72         category_code => $categorycode
73     }
74 });
75
76 my $borrower = $builder->build({
77     source => 'Borrower',
78     value => {
79         userid => 'hola',
80         branchcode   => $branchcode,
81         categorycode => $categorycode
82     }
83 });
84
85 $builder->build({
86     source => 'BorrowerAttribute',
87     value => {
88         borrowernumber => $borrower->{borrowernumber},
89         code => $attrType->{code},
90         attribute => 'FOO'
91     }
92 });
93
94 # C4::Auth_with_ldap needs several stuff set first ^^^
95 use_ok( 'C4::Auth_with_ldap' );
96 can_ok( 'C4::Auth_with_ldap', qw/
97         checkpw_ldap
98         search_method /);
99
100 subtest "checkpw_ldap tests" => sub {
101
102     plan tests => 4;
103
104     ## Connection fail tests
105     $desired_connection_result = 'error';
106     warning_is { $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' ) }
107         "LDAP connexion failed",
108         "checkpw_ldap prints correct warning if LDAP conexion fails";
109     is( $ret, 0, "checkpw_ldap returns 0 if LDAP conexion fails");
110
111     ## Connection success tests
112     $desired_connection_result = 'success';
113
114     subtest "auth_by_bind = 1 tests" => sub {
115
116         plan tests => 8;
117
118         $auth_by_bind          = 1;
119
120         $desired_authentication_result = 'success';
121         $anonymous_bind        = 1;
122         $desired_bind_result   = 'error';
123         $desired_search_result = 'error';
124         reload_ldap_module();
125
126
127         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
128                                $dbh, 'hola', password => 'hey' ) }
129                     qr/Anonymous LDAP bind failed: LDAP error #1: error_name/,
130                     "checkpw_ldap prints correct warning if LDAP anonymous bind fails";
131         is( $ret, 0, "checkpw_ldap returns 0 if LDAP anonymous bind fails");
132
133         $desired_authentication_result = 'success';
134         $anonymous_bind        = 1;
135         $desired_bind_result   = 'success';
136         $desired_search_result = 'success';
137         $desired_count_result  = 1;
138         $non_anonymous_bind_result = 'success';
139         $update = 1;
140         reload_ldap_module();
141
142         my $auth = new Test::MockModule('C4::Auth_with_ldap');
143         $auth->mock( 'update_local', sub {
144                 return $borrower->{cardnumber};
145         });
146
147         C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey');
148         ok(@{ C4::Members::Attributes::GetBorrowerAttributes($borrower->{borrowernumber}) }, 'Extended attributes are not deleted');
149         $auth->unmock('update_local');
150
151         $update = 0;
152         $desired_count_result = 0; # user auth problem
153         C4::Members::DelMember($borrower->{borrowernumber});
154         reload_ldap_module();
155         is ( C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' ),
156             0, "checkpw_ldap returns 0 if user lookup returns 0");
157
158         $non_anonymous_bind_result = 'error';
159         reload_ldap_module();
160
161         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
162                                $dbh, 'hola', password => 'hey' ) }
163                     qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
164                     "checkpw_ldap prints correct warning if LDAP bind fails";
165         is ( $ret, -1, "checkpw_ldap returns -1 LDAP bind fails for user (Bug 8148)");
166
167         # regression tests for bug 12831
168         $desired_authentication_result = 'error';
169         $anonymous_bind        = 0;
170         $desired_bind_result   = 'error';
171         $desired_search_result = 'success';
172         $desired_count_result  = 0; # user auth problem
173         $non_anonymous_bind_result = 'error';
174         reload_ldap_module();
175
176         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
177                                $dbh, 'hola', password => 'hey' ) }
178                     qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
179                     "checkpw_ldap prints correct warning if LDAP bind fails";
180         is ( $ret, 0, "checkpw_ldap returns 0 LDAP bind fails for user (Bug 12831)");
181
182     };
183
184     subtest "auth_by_bind = 0 tests" => sub {
185
186         plan tests => 8;
187
188         $auth_by_bind = 0;
189
190         # Anonymous bind
191         $anonymous_bind            = 1;
192         $desired_bind_result       = 'error';
193         $non_anonymous_bind_result = 'error';
194         reload_ldap_module();
195
196         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
197                                $dbh, 'hola', password => 'hey' ) }
198                     qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
199                     "checkpw_ldap prints correct warning if LDAP bind fails";
200         is ( $ret, 0, "checkpw_ldap returns 0 if bind fails");
201
202         $anonymous_bind            = 1;
203         $desired_bind_result       = 'success';
204         $non_anonymous_bind_result = 'success';
205         $desired_compare_result    = 'error';
206         reload_ldap_module();
207
208         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
209                                $dbh, 'hola', password => 'hey' ) }
210                     qr/LDAP Auth rejected : invalid password for user 'hola'. LDAP error #1: error_name/,
211                     "checkpw_ldap prints correct warning if LDAP bind fails";
212         is ( $ret, -1, "checkpw_ldap returns -1 if bind fails (Bug 8148)");
213
214         # Non-anonymous bind
215         $anonymous_bind            = 0;
216         $desired_bind_result       = 'success';
217         $non_anonymous_bind_result = 'error';
218         $desired_compare_result    = 'dont care';
219         reload_ldap_module();
220
221         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
222                                $dbh, 'hola', password => 'hey' ) }
223                     qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
224                     "checkpw_ldap prints correct warning if LDAP bind fails";
225         is ( $ret, 0, "checkpw_ldap returns 0 if bind fails");
226
227         $anonymous_bind            = 0;
228         $desired_bind_result       = 'success';
229         $non_anonymous_bind_result = 'success';
230         $desired_compare_result    = 'error';
231         reload_ldap_module();
232
233         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
234                                $dbh, 'hola', password => 'hey' ) }
235                     qr/LDAP Auth rejected : invalid password for user 'hola'. LDAP error #1: error_name/,
236                     "checkpw_ldap prints correct warning if LDAP bind fails";
237         is ( $ret, -1, "checkpw_ldap returns -1 if bind fails (Bug 8148)");
238
239     };
240 };
241
242 subtest "search_method tests" => sub {
243
244     plan tests => 5;
245
246     my $ldap = mock_net_ldap();
247
248     # Null params tests
249     is( C4::Auth_with_ldap::search_method( $ldap, undef), undef,
250         "search_method returns undef on undefined userid");
251     is( C4::Auth_with_ldap::search_method( undef, "undef"), undef,
252         "search_method returns undef on undefined ldap object");
253
254     # search ->code and !->code
255     $desired_search_result = 'error';
256     reload_ldap_module();
257     eval { $ret = C4::Auth_with_ldap::search_method( $ldap, "undef"); };
258     like( $@, qr/LDAP search failed to return object : 1/,
259         "search_method prints correct warning when db->search returns error code");
260
261     $desired_search_result = 'success';
262     $desired_count_result  = 2;
263     reload_ldap_module();
264     warning_like { $ret = C4::Auth_with_ldap::search_method( $ldap, '123') }
265                    qr/^LDAP Auth rejected \: \(uid\=123\) gets 2 hits/,
266                    "search_method prints correct warning when hits count is not 1";
267     is( $ret, 0, "search_method returns 0 when hits count is not 1" );
268
269 };
270
271 # Function that mocks the call to C4::Context->config(param)
272 sub mockedC4Config {
273     my $class = shift;
274     my $param =  shift;
275
276     if ($param eq 'useshibboleth') {
277         return 0;
278     }
279     elsif ($param eq 'ldapserver') {
280         my %ldap_mapping = (
281             firstname    => { is => 'givenname' },
282             surname      => { is => 'sn' },
283             address      => { is => 'postaladdress' },
284             city         => { is => 'l' },
285             zipcode      => { is => 'postalcode' },
286             branchcode   => { is => 'branch' },
287             userid       => { is => 'uid' },
288             password     => { is => 'userpassword' },
289             email        => { is => 'mail' },
290             categorycode => { is => 'employeetype' },
291             phone        => { is => 'telephonenumber' }
292         );
293
294         my %ldap_config  = (
295             anonymous_bind => $anonymous_bind,
296             auth_by_bind   => $auth_by_bind,
297             base           => 'dc=metavore,dc=com',
298             hostname       => 'localhost',
299             mapping        => \%ldap_mapping,
300             pass           => 'metavore',
301             principal_name => '%s@my_domain.com',
302             replicate      => $replicate,
303             update         => $update,
304             user           => 'cn=Manager,dc=metavore,dc=com'
305         );
306         return \%ldap_config;
307     }
308     elsif ($param =~ /(intranetdir|opachtdocs|intrahtdocs)/ ) {
309         return '';
310     }
311     elsif (ref $class eq 'HASH') {
312         return $class->{$param};
313     }
314     else {
315         return;
316     }
317 };
318
319 # Function that mocks the call to Net::LDAP
320 sub mock_net_ldap {
321
322     my $mocked_ldap = Test::MockObject->new();
323
324     $mocked_ldap->mock( 'bind', sub {
325
326         my @args = @_;
327         my $mocked_message;
328
329         if ( $#args > 1 ) {
330             # Args passed => non-anonymous bind
331             if ( $non_anonymous_bind_result eq 'error' ) {
332                 return mock_net_ldap_message(1,1,'error_name','error_text');
333             } else {
334                 return mock_net_ldap_message(0,0,'','');
335             }
336         } else {
337             $mocked_message = mock_net_ldap_message(
338                 ($desired_bind_result eq 'error' ) ? 1 : 0, # code
339                 ($desired_bind_result eq 'error' ) ? 1 : 0, # error
340                 ($desired_bind_result eq 'error' ) ? 'error_name' : 0, # error_name
341                 ($desired_bind_result eq 'error' ) ? 'error_text' : 0  # error_text
342             );
343         }
344
345         return $mocked_message;
346     });
347
348     $mocked_ldap->mock( 'compare', sub {
349
350         my $mocked_message;
351
352         if ( $desired_compare_result eq 'error' ) {
353             $mocked_message = mock_net_ldap_message(1,1,'error_name','error_text');
354         } else {
355             # we expect return code 6 for success
356             $mocked_message = mock_net_ldap_message(6,0,'','');
357         }
358
359         return $mocked_message;
360     });
361
362     $mocked_ldap->mock( 'search', sub {
363
364         return mock_net_ldap_search(
365             ( $desired_count_result )             # count
366                 ? $desired_count_result
367                 : 1, # default to 1
368             ( $desired_search_result eq 'error' ) # code
369                 ? 1
370                 : 0, # 0 == success
371             ( $desired_search_result eq 'error' ) # error
372                 ? 1
373                 : 0,
374             ( $desired_search_result eq 'error' ) # error_text
375                 ? 'error_text'
376                 : undef,
377             ( $desired_search_result eq 'error' ) # error_name
378                 ? 'error_name'
379                 : undef,
380             mock_net_ldap_entry( 'sampledn', 1 )  # shift_entry
381         );
382
383     });
384
385     return $mocked_ldap;
386 }
387
388 sub mock_net_ldap_search {
389     my ( $count, $code, $error, $error_text,
390          $error_name, $shift_entry ) = @_;
391
392     my $mocked_search = Test::MockObject->new();
393     $mocked_search->mock( 'count',       sub { return $count; } );
394     $mocked_search->mock( 'code',        sub { return $code; } );
395     $mocked_search->mock( 'error',       sub { return $error; } );
396     $mocked_search->mock( 'error_name',  sub { return $error_name; } );
397     $mocked_search->mock( 'error_text',  sub { return $error_text; } );
398     $mocked_search->mock( 'shift_entry', sub { return $shift_entry; } );
399
400     return $mocked_search;
401 }
402
403 sub mock_net_ldap_message {
404     my ( $code, $error, $error_name, $error_text ) = @_;
405
406     my $mocked_message = Test::MockObject->new();
407     $mocked_message->mock( 'code',       sub { $code } );
408     $mocked_message->mock( 'error',      sub { $error } );
409     $mocked_message->mock( 'error_name', sub { $error_name } );
410     $mocked_message->mock( 'error_text', sub { $error_text } );
411
412     return $mocked_message;
413 }
414
415 sub mock_net_ldap_entry {
416     my ( $dn, $exists ) = @_;
417
418     my $mocked_entry = Test::MockObject->new();
419     $mocked_entry->mock( 'dn',     sub { return $dn; } );
420     $mocked_entry->mock( 'exists', sub { return $exists } );
421
422     return $mocked_entry;
423 }
424
425 # TODO: Once we remove the global variables in C4::Auth_with_ldap
426 # we shouldn't need this...
427 # ... Horrible hack
428 sub reload_ldap_module {
429     delete $INC{'C4/Auth_with_ldap.pm'};
430     require C4::Auth_with_ldap;
431     C4::Auth_with_ldap->import;
432 }
433
434 $dbh->rollback;
435
436 1;