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