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