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