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