Bug 14144: Clean ups and refactors
[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
30 # Start transaction
31 $dbh->{AutoCommit} = 0;
32 $dbh->{RaiseError} = 1;
33
34 my $builder = t::lib::TestBuilder->new();
35
36 # Variables controlling LDAP server config
37 my $update         = 0;
38 my $replicate      = 0;
39 my $auth_by_bind   = 1;
40 my $anonymous_bind = 1;
41
42 # Variables controlling LDAP behaviour
43 my $desired_authentication_result = 'success';
44 my $desired_connection_result     = 'error';
45 my $desired_bind_result           = 'error';
46 my $desired_compare_result        = 'error';
47 my $desired_search_result         = 'error';
48 my $desired_count_result          = 1;
49 my $non_anonymous_bind_result     = 'error';
50 my $ret;
51
52 # Mock the context module
53 my $context = Test::MockModule->new('C4::Context');
54 $context->mock( 'config', \&mockedC4Config );
55
56 # Mock the Net::LDAP module
57 my $net_ldap = Test::MockModule->new('Net::LDAP');
58
59 $net_ldap->mock(
60     'new',
61     sub {
62         if ( $desired_connection_result eq 'error' ) {
63
64             # We were asked to fail the LDAP conexion
65             return;
66         }
67         else {
68             # Return a mocked Net::LDAP object (Test::MockObject)
69             return mock_net_ldap();
70         }
71     }
72 );
73
74 my $categorycode = $builder->build( { source => 'Category' } )->{categorycode};
75 my $branchcode   = $builder->build( { source => 'Branch' } )->{branchcode};
76 my $attr_type    = $builder->build(
77     {
78         source => 'BorrowerAttributeType',
79         value  => {
80             category_code => $categorycode
81         }
82     }
83 );
84
85 my $borrower = $builder->build(
86     {
87         source => 'Borrower',
88         value  => {
89             userid       => 'hola',
90             branchcode   => $branchcode,
91             categorycode => $categorycode
92         }
93     }
94 );
95
96 $builder->build(
97     {
98         source => 'BorrowerAttribute',
99         value  => {
100             borrowernumber => $borrower->{borrowernumber},
101             code           => $attr_type->{code},
102             attribute      => 'FOO'
103         }
104     }
105 );
106
107 # C4::Auth_with_ldap needs several stuff set first ^^^
108 use_ok('C4::Auth_with_ldap');
109 can_ok(
110     'C4::Auth_with_ldap', qw/
111       checkpw_ldap
112       search_method /
113 );
114
115 subtest 'checkpw_ldap tests' => sub {
116
117     plan tests => 4;
118
119     ## Connection fail tests
120     $desired_connection_result = 'error';
121     warning_is {
122         $ret =
123           C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' );
124     }
125     'LDAP connexion failed',
126       'checkpw_ldap prints correct warning if LDAP conexion fails';
127     is( $ret, 0, 'checkpw_ldap returns 0 if LDAP conexion fails' );
128
129     ## Connection success tests
130     $desired_connection_result = 'success';
131
132     subtest 'auth_by_bind = 1 tests' => sub {
133
134         plan tests => 8;
135
136         $auth_by_bind = 1;
137
138         $desired_authentication_result = 'success';
139         $anonymous_bind                = 1;
140         $desired_bind_result           = 'error';
141         $desired_search_result         = 'error';
142         reload_ldap_module();
143
144         warning_like {
145             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
146                 password => 'hey' );
147         }
148         qr/Anonymous LDAP bind failed: LDAP error #1: error_name/,
149           'checkpw_ldap prints correct warning if LDAP anonymous bind fails';
150         is( $ret, 0, 'checkpw_ldap returns 0 if LDAP anonymous bind fails' );
151
152         $desired_authentication_result = 'success';
153         $anonymous_bind                = 1;
154         $desired_bind_result           = 'success';
155         $desired_search_result         = 'success';
156         $desired_count_result          = 1;
157         $non_anonymous_bind_result     = 'success';
158         $update                        = 1;
159         reload_ldap_module();
160
161         my $auth = Test::MockModule->new('C4::Auth_with_ldap');
162         $auth->mock(
163             'update_local',
164             sub {
165                 return $borrower->{cardnumber};
166             }
167         );
168
169         C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' );
170         ok(
171             @{
172                 C4::Members::Attributes::GetBorrowerAttributes(
173                     $borrower->{borrowernumber}
174                 )
175             },
176             'Extended attributes are not deleted'
177         );
178         $auth->unmock('update_local');
179
180         $update               = 0;
181         $desired_count_result = 0;    # user auth problem
182         C4::Members::DelMember( $borrower->{borrowernumber} );
183         reload_ldap_module();
184         is(
185             C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' ),
186             0,
187             'checkpw_ldap returns 0 if user lookup returns 0'
188         );
189
190         $non_anonymous_bind_result = 'error';
191         reload_ldap_module();
192
193         warning_like {
194             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
195                 password => 'hey' );
196         }
197         qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
198           'checkpw_ldap prints correct warning if LDAP bind fails';
199         is( $ret, -1,
200             'checkpw_ldap returns -1 LDAP bind fails for user (Bug 8148)' );
201
202         # regression tests for bug 12831
203         $desired_authentication_result = 'error';
204         $anonymous_bind                = 0;
205         $desired_bind_result           = 'error';
206         $desired_search_result         = 'success';
207         $desired_count_result          = 0;           # user auth problem
208         $non_anonymous_bind_result     = 'error';
209         reload_ldap_module();
210
211         warning_like {
212             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
213                 password => 'hey' );
214         }
215         qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
216           'checkpw_ldap prints correct warning if LDAP bind fails';
217         is( $ret, 0,
218             'checkpw_ldap returns 0 LDAP bind fails for user (Bug 12831)' );
219
220     };
221
222     subtest 'auth_by_bind = 0 tests' => sub {
223
224         plan tests => 8;
225
226         $auth_by_bind = 0;
227
228         # Anonymous bind
229         $anonymous_bind            = 1;
230         $desired_bind_result       = 'error';
231         $non_anonymous_bind_result = 'error';
232         reload_ldap_module();
233
234         warning_like {
235             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
236                 password => 'hey' );
237         }
238 qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
239           'checkpw_ldap prints correct warning if LDAP bind fails';
240         is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' );
241
242         $anonymous_bind            = 1;
243         $desired_bind_result       = 'success';
244         $non_anonymous_bind_result = 'success';
245         $desired_compare_result    = 'error';
246         reload_ldap_module();
247
248         warning_like {
249             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
250                 password => 'hey' );
251         }
252 qr/LDAP Auth rejected : invalid password for user 'hola'. LDAP error #1: error_name/,
253           'checkpw_ldap prints correct warning if LDAP bind fails';
254         is( $ret, -1, 'checkpw_ldap returns -1 if bind fails (Bug 8148)' );
255
256         # Non-anonymous bind
257         $anonymous_bind            = 0;
258         $desired_bind_result       = 'success';
259         $non_anonymous_bind_result = 'error';
260         $desired_compare_result    = 'dont care';
261         reload_ldap_module();
262
263         warning_like {
264             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
265                 password => 'hey' );
266         }
267 qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
268           'checkpw_ldap prints correct warning if LDAP bind fails';
269         is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' );
270
271         $anonymous_bind            = 0;
272         $desired_bind_result       = 'success';
273         $non_anonymous_bind_result = 'success';
274         $desired_compare_result    = 'error';
275         reload_ldap_module();
276
277         warning_like {
278             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
279                 password => 'hey' );
280         }
281 qr/LDAP Auth rejected : invalid password for user 'hola'. LDAP error #1: error_name/,
282           'checkpw_ldap prints correct warning if LDAP bind fails';
283         is( $ret, -1, 'checkpw_ldap returns -1 if bind fails (Bug 8148)' );
284
285     };
286 };
287
288 subtest 'search_method tests' => sub {
289
290     plan tests => 5;
291
292     my $ldap = mock_net_ldap();
293
294     # Null params tests
295     is( C4::Auth_with_ldap::search_method( $ldap, undef ),
296         undef, 'search_method returns undef on undefined userid' );
297     is( C4::Auth_with_ldap::search_method( undef, 'undef' ),
298         undef, 'search_method returns undef on undefined ldap object' );
299
300     # search ->code and !->code
301     $desired_search_result = 'error';
302     reload_ldap_module();
303     my $eval_retval =
304       eval { $ret = C4::Auth_with_ldap::search_method( $ldap, 'undef' ); };
305     like(
306         $@,
307         qr/LDAP search failed to return object : 1/,
308 'search_method prints correct warning when db->search returns error code'
309     );
310
311     $desired_search_result = 'success';
312     $desired_count_result  = 2;
313     reload_ldap_module();
314     warning_like { $ret = C4::Auth_with_ldap::search_method( $ldap, '123' ) }
315     qr/^LDAP Auth rejected \: \(uid\=123\) gets 2 hits/,
316       'search_method prints correct warning when hits count is not 1';
317     is( $ret, 0, 'search_method returns 0 when hits count is not 1' );
318
319 };
320
321 # Function that mocks the call to C4::Context->config(param)
322 sub mockedC4Config {
323     my $class = shift;
324     my $param = shift;
325
326     if ( $param eq 'useshibboleth' ) {
327         return 0;
328     }
329     if ( $param eq 'ldapserver' ) {
330         my %ldap_mapping = (
331             firstname    => { is => 'givenname' },
332             surname      => { is => 'sn' },
333             address      => { is => 'postaladdress' },
334             city         => { is => 'l' },
335             zipcode      => { is => 'postalcode' },
336             branchcode   => { is => 'branch' },
337             userid       => { is => 'uid' },
338             password     => { is => 'userpassword' },
339             email        => { is => 'mail' },
340             categorycode => { is => 'employeetype' },
341             phone        => { is => 'telephonenumber' },
342         );
343
344         my %ldap_config = (
345             anonymous_bind => $anonymous_bind,
346             auth_by_bind   => $auth_by_bind,
347             base           => 'dc=metavore,dc=com',
348             hostname       => 'localhost',
349             mapping        => \%ldap_mapping,
350             pass           => 'metavore',
351             principal_name => '%s@my_domain.com',
352             replicate      => $replicate,
353             update         => $update,
354             user           => 'cn=Manager,dc=metavore,dc=com',
355         );
356         return \%ldap_config;
357     }
358     if ( $param =~ /(intranetdir|opachtdocs|intrahtdocs)/x ) {
359         return q{};
360     }
361     if ( ref $class eq 'HASH' ) {
362         return $class->{$param};
363     }
364     return;
365 }
366
367 # Function that mocks the call to Net::LDAP
368 sub mock_net_ldap {
369
370     my $mocked_ldap = Test::MockObject->new();
371
372     $mocked_ldap->mock(
373         'bind',
374         sub {
375
376             my @args = @_;
377             my $mocked_message;
378
379             if ( $#args > 1 ) {
380
381                 # Args passed => non-anonymous bind
382                 if ( $non_anonymous_bind_result eq 'error' ) {
383                     return mock_net_ldap_message( 1, 1, 'error_name',
384                         'error_text' );
385                 }
386                 else {
387                     return mock_net_ldap_message( 0, 0, q{}, q{} );
388                 }
389             }
390             else {
391                 $mocked_message = mock_net_ldap_message(
392                     ( $desired_bind_result eq 'error' ) ? 1 : 0,    # code
393                     ( $desired_bind_result eq 'error' ) ? 1 : 0,    # error
394                     ( $desired_bind_result eq 'error' )
395                     ? 'error_name'
396                     : 0,                                            # error_name
397                     ( $desired_bind_result eq 'error' )
398                     ? 'error_text'
399                     : 0                                             # error_text
400                 );
401             }
402
403             return $mocked_message;
404         }
405     );
406
407     $mocked_ldap->mock(
408         'compare',
409         sub {
410
411             my $mocked_message;
412
413             if ( $desired_compare_result eq 'error' ) {
414                 $mocked_message =
415                   mock_net_ldap_message( 1, 1, 'error_name', 'error_text' );
416             }
417             else {
418                 # we expect return code 6 for success
419                 $mocked_message = mock_net_ldap_message( 6, 0, q{}, q{} );
420             }
421
422             return $mocked_message;
423         }
424     );
425
426     $mocked_ldap->mock(
427         'search',
428         sub {
429
430             return mock_net_ldap_search(
431                 {
432                     count => ($desired_count_result)
433                     ? $desired_count_result
434                     : 1,    # default to 1
435                     code => ( $desired_search_result eq 'error' )
436                     ? 1
437                     : 0,    # 0 == success
438                     error => ( $desired_search_result eq 'error' ) ? 1
439                     : 0,
440                     error_text => ( $desired_search_result eq 'error' )
441                     ? 'error_text'
442                     : undef,
443                     error_name => ( $desired_search_result eq 'error' )
444                     ? 'error_name'
445                     : undef,
446                     shift_entry => mock_net_ldap_entry( 'sampledn', 1 )
447                 }
448             );
449
450         }
451     );
452
453     return $mocked_ldap;
454 }
455
456 sub mock_net_ldap_search {
457     my ($parameters) = @_;
458
459     my $count       = $parameters->{count};
460     my $code        = $parameters->{code};
461     my $error       = $parameters->{error};
462     my $error_text  = $parameters->{error_text};
463     my $error_name  = $parameters->{error_name};
464     my $shift_entry = $parameters->{shift_entry};
465
466     my $mocked_search = Test::MockObject->new();
467     $mocked_search->mock( 'count',       sub { return $count; } );
468     $mocked_search->mock( 'code',        sub { return $code; } );
469     $mocked_search->mock( 'error',       sub { return $error; } );
470     $mocked_search->mock( 'error_name',  sub { return $error_name; } );
471     $mocked_search->mock( 'error_text',  sub { return $error_text; } );
472     $mocked_search->mock( 'shift_entry', sub { return $shift_entry; } );
473
474     return $mocked_search;
475 }
476
477 sub mock_net_ldap_message {
478     my ( $code, $error, $error_name, $error_text ) = @_;
479
480     my $mocked_message = Test::MockObject->new();
481     $mocked_message->mock( 'code',       sub { $code } );
482     $mocked_message->mock( 'error',      sub { $error } );
483     $mocked_message->mock( 'error_name', sub { $error_name } );
484     $mocked_message->mock( 'error_text', sub { $error_text } );
485
486     return $mocked_message;
487 }
488
489 sub mock_net_ldap_entry {
490     my ( $dn, $exists ) = @_;
491
492     my $mocked_entry = Test::MockObject->new();
493     $mocked_entry->mock( 'dn',     sub { return $dn; } );
494     $mocked_entry->mock( 'exists', sub { return $exists } );
495
496     return $mocked_entry;
497 }
498
499 # TODO: Once we remove the global variables in C4::Auth_with_ldap
500 # we shouldn't need this...
501 # ... Horrible hack
502 sub reload_ldap_module {
503     delete $INC{'C4/Auth_with_ldap.pm'};
504     require C4::Auth_with_ldap;
505     C4::Auth_with_ldap->import;
506     return;
507 }
508
509 $dbh->rollback;
510
511 1;