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