Bug 14334: Remove AutoCommit from 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 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 # C4::Auth_with_ldap needs several stuff set first ^^^
121 use_ok('C4::Auth_with_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     my $dbh = C4::Context->dbh;
133     ## Connection fail tests
134     $desired_connection_result = 'error';
135     warning_is {
136         $ret =
137           C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' );
138     }
139     'LDAP connexion failed',
140       'checkpw_ldap prints correct warning if LDAP conexion fails';
141     is( $ret, 0, 'checkpw_ldap returns 0 if LDAP conexion fails' );
142
143     ## Connection success tests
144     $desired_connection_result = 'success';
145
146     subtest 'auth_by_bind = 1 tests' => sub {
147
148         plan tests => 11;
149
150         $auth_by_bind = 1;
151
152         $desired_authentication_result = 'success';
153         $anonymous_bind                = 1;
154         $desired_admin_bind_result   = 'error';
155         $desired_search_result         = 'error';
156         reload_ldap_module();
157
158         warning_like {
159             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
160                 password => 'hey' );
161         }
162         qr/Anonymous LDAP bind failed: LDAP error #1: error_name/,
163           'checkpw_ldap prints correct warning if LDAP anonymous bind fails';
164         is( $ret, 0, 'checkpw_ldap returns 0 if LDAP anonymous bind fails' );
165
166         $anonymous_bind = 0;
167         $user = undef;
168         $pass = undef;
169         reload_ldap_module();
170
171         warning_like {
172             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
173                 password => 'hey' );
174         }
175         qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
176           'checkpw_ldap prints correct warning if LDAP bind_by_auth fails';
177         is( $ret, 0, 'checkpw_ldap returns 0 if LDAP bind_by_auth fails' );
178
179         $desired_authentication_result = 'success';
180         $anonymous_bind                = 1;
181         $desired_admin_bind_result   = 'success';
182         $desired_search_result         = 'success';
183         $desired_count_result          = 1;
184         $desired_bind_result = 'success';
185         $update                        = 1;
186         reload_ldap_module();
187
188         t::lib::Mocks::mock_preference( 'ExtendedPatronAttributes', 1 );
189         my $auth = Test::MockModule->new('C4::Auth_with_ldap');
190         $auth->mock(
191             'update_local',
192             sub {
193                 return $borrower->{cardnumber};
194             }
195         );
196         $auth->mock(
197             'ldap_entry_2_hash',
198             sub {
199                 return (
200                     $attr_type2->{code}, 'BAR'
201                 );
202             }
203         );
204
205         C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' );
206         ok(
207             @{
208                 C4::Members::Attributes::GetBorrowerAttributes(
209                     $borrower->{borrowernumber}
210                 )
211             },
212             'Extended attributes are not deleted'
213         );
214
215         is( C4::Members::Attributes::GetBorrowerAttributeValue($borrower->{borrowernumber}, $attr_type2->{code}), 'BAR', 'Mapped attribute is BAR' );
216         $auth->unmock('update_local');
217         $auth->unmock('ldap_entry_2_hash');
218
219         $update               = 0;
220         $desired_count_result = 0;    # user auth problem
221         Koha::Patrons->find( $borrower->{borrowernumber} )->delete;
222         reload_ldap_module();
223         is(
224             C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' ),
225             0,
226             'checkpw_ldap returns 0 if user lookup returns 0'
227         );
228
229         $desired_bind_result = 'error';
230         reload_ldap_module();
231
232         warning_like {
233             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
234                 password => 'hey' );
235         }
236         qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
237           'checkpw_ldap prints correct warning if LDAP bind fails';
238         is( $ret, -1,
239             'checkpw_ldap returns -1 LDAP bind fails for user (Bug 8148)' );
240
241         # regression tests for bug 12831
242         $desired_authentication_result = 'error';
243         $anonymous_bind                = 0;
244         $desired_admin_bind_result   = 'error';
245         $desired_search_result         = 'success';
246         $desired_count_result          = 0;           # user auth problem
247         $desired_bind_result = 'error';
248         reload_ldap_module();
249
250         warning_like {
251             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
252                 password => 'hey' );
253         }
254         qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
255           'checkpw_ldap prints correct warning if LDAP bind fails';
256         is( $ret, 0,
257             'checkpw_ldap returns 0 LDAP bind fails for user (Bug 12831)' );
258
259     };
260
261     subtest 'auth_by_bind = 0 tests' => sub {
262
263         plan tests => 8;
264
265         $auth_by_bind = 0;
266
267         # Anonymous bind
268         $anonymous_bind            = 1;
269         $user                      = 'cn=Manager,dc=metavore,dc=com';
270         $pass                      = 'metavore';
271         $desired_admin_bind_result = 'error';
272         $desired_bind_result       = 'error';
273         reload_ldap_module();
274
275         warning_like {
276             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
277                 password => 'hey' );
278         }
279 qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
280           'checkpw_ldap prints correct warning if LDAP bind fails';
281         is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' );
282
283         $anonymous_bind            = 1;
284         $desired_admin_bind_result = 'success';
285         $desired_bind_result = 'error';
286         $desired_search_result = 'success';
287         $desired_count_result = 1;
288         reload_ldap_module();
289
290         warning_like {
291             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
292                 password => 'hey' );
293         }
294 qr/LDAP Auth rejected : invalid password for user 'hola'./,
295           'checkpw_ldap prints correct warning if LDAP bind fails';
296         is( $ret, -1, 'checkpw_ldap returns -1 if bind fails (Bug 8148)' );
297
298         # Non-anonymous bind
299         $anonymous_bind            = 0;
300         $desired_admin_bind_result = 'error';
301         $desired_bind_result = 'error';
302         reload_ldap_module();
303
304         warning_like {
305             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
306                 password => 'hey' );
307         }
308 qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
309           'checkpw_ldap prints correct warning if LDAP bind fails';
310         is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' );
311
312         $anonymous_bind            = 0;
313         $desired_admin_bind_result = 'success';
314         $desired_bind_result = 'error';
315         reload_ldap_module();
316
317         warning_like {
318             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
319                 password => 'hey' );
320         }
321 qr/LDAP Auth rejected : invalid password for user 'hola'./,
322           'checkpw_ldap prints correct warning if LDAP bind fails';
323         is( $ret, -1, 'checkpw_ldap returns -1 if bind fails (Bug 8148)' );
324
325     };
326 };
327
328 subtest 'search_method tests' => sub {
329
330     plan tests => 3;
331
332     my $ldap = mock_net_ldap();
333
334     # Null params tests
335     is( C4::Auth_with_ldap::search_method( $ldap, undef ),
336         undef, 'search_method returns undef on undefined userid' );
337     is( C4::Auth_with_ldap::search_method( undef, 'undef' ),
338         undef, 'search_method returns undef on undefined ldap object' );
339
340     # search ->code and !->code
341     $desired_search_result = 'error';
342     reload_ldap_module();
343     my $eval_retval =
344       eval { $ret = C4::Auth_with_ldap::search_method( $ldap, 'undef' ); };
345     like(
346         $@,
347         qr/LDAP search failed to return object : 1/,
348 'search_method prints correct warning when db->search returns error code'
349     );
350 };
351
352 # Function that mocks the call to C4::Context->config(param)
353 sub mockedC4Config {
354     my $class = shift;
355     my $param = shift;
356
357     if ( $param eq 'useshibboleth' ) {
358         return 0;
359     }
360     if ( $param eq 'ldapserver' ) {
361         my %ldap_mapping = (
362             firstname    => { is => 'givenname' },
363             surname      => { is => 'sn' },
364             address      => { is => 'postaladdress' },
365             city         => { is => 'l' },
366             zipcode      => { is => 'postalcode' },
367             branchcode   => { is => 'branch' },
368             userid       => { is => 'uid' },
369             password     => { is => 'userpassword' },
370             email        => { is => 'mail' },
371             categorycode => { is => 'employeetype' },
372             phone        => { is => 'telephonenumber' },
373         );
374
375         my %ldap_config = (
376             anonymous_bind => $anonymous_bind,
377             auth_by_bind   => $auth_by_bind,
378             base           => 'dc=metavore,dc=com',
379             hostname       => 'localhost',
380             mapping        => \%ldap_mapping,
381             pass           => $pass,
382             principal_name => '%s@my_domain.com',
383             replicate      => $replicate,
384             update         => $update,
385             user           => $user,
386         );
387         return \%ldap_config;
388     }
389     if ( $param =~ /(intranetdir|opachtdocs|intrahtdocs)/x ) {
390         return q{};
391     }
392     if ( ref $class eq 'HASH' ) {
393         return $class->{$param};
394     }
395     return;
396 }
397
398 # Function that mocks the call to Net::LDAP
399 sub mock_net_ldap {
400
401     my $mocked_ldap = Test::MockObject->new();
402
403     $mocked_ldap->mock( 'bind', sub {
404         if (is_admin_bind(@_)) {
405             return mock_net_ldap_message(
406                 ($desired_admin_bind_result eq 'error' ) ? 1 : 0, # code
407                 ($desired_admin_bind_result eq 'error' ) ? 1 : 0, # error
408                 ($desired_admin_bind_result eq 'error' ) ? 'error_name' : 0, # error_name
409                 ($desired_admin_bind_result eq 'error' ) ? 'error_text' : 0  # error_text
410             );
411         }
412         else {
413             if ( $desired_bind_result eq 'error' ) {
414                 return mock_net_ldap_message(1,1,'error_name','error_text');
415             }
416             return mock_net_ldap_message(0,0,'','');
417         }
418     });
419
420     $mocked_ldap->mock(
421         'search',
422         sub {
423
424             $remaining_entry = 1;
425
426             return mock_net_ldap_search(
427                 {
428                     count => ($desired_count_result)
429                     ? $desired_count_result
430                     : 1,    # default to 1
431                     code => ( $desired_search_result eq 'error' )
432                     ? 1
433                     : 0,    # 0 == success
434                     error => ( $desired_search_result eq 'error' ) ? 1
435                     : 0,
436                     error_text => ( $desired_search_result eq 'error' )
437                     ? 'error_text'
438                     : undef,
439                     error_name => ( $desired_search_result eq 'error' )
440                     ? 'error_name'
441                     : undef,
442                     shift_entry => mock_net_ldap_entry( 'sampledn', 1 )
443                 }
444             );
445
446         }
447     );
448
449     return $mocked_ldap;
450 }
451
452 sub mock_net_ldap_search {
453     my ($parameters) = @_;
454
455     my $count       = $parameters->{count};
456     my $code        = $parameters->{code};
457     my $error       = $parameters->{error};
458     my $error_text  = $parameters->{error_text};
459     my $error_name  = $parameters->{error_name};
460     my $shift_entry = $parameters->{shift_entry};
461
462     my $mocked_search = Test::MockObject->new();
463     $mocked_search->mock( 'count',       sub { return $count; } );
464     $mocked_search->mock( 'code',        sub { return $code; } );
465     $mocked_search->mock( 'error',       sub { return $error; } );
466     $mocked_search->mock( 'error_name',  sub { return $error_name; } );
467     $mocked_search->mock( 'error_text',  sub { return $error_text; } );
468     $mocked_search->mock( 'shift_entry', sub {
469         if ($remaining_entry) {
470             $remaining_entry--;
471             return $shift_entry;
472         }
473         return '';
474     });
475
476     return $mocked_search;
477 }
478
479 sub mock_net_ldap_message {
480     my ( $code, $error, $error_name, $error_text ) = @_;
481
482     my $mocked_message = Test::MockObject->new();
483     $mocked_message->mock( 'code',       sub { $code } );
484     $mocked_message->mock( 'error',      sub { $error } );
485     $mocked_message->mock( 'error_name', sub { $error_name } );
486     $mocked_message->mock( 'error_text', sub { $error_text } );
487
488     return $mocked_message;
489 }
490
491 sub mock_net_ldap_entry {
492     my ( $dn, $exists ) = @_;
493
494     my $mocked_entry = Test::MockObject->new();
495     $mocked_entry->mock( 'dn',     sub { return $dn; } );
496     $mocked_entry->mock( 'exists', sub { return $exists } );
497
498     return $mocked_entry;
499 }
500
501 # TODO: Once we remove the global variables in C4::Auth_with_ldap
502 # we shouldn't need this...
503 # ... Horrible hack
504 sub reload_ldap_module {
505     delete $INC{'C4/Auth_with_ldap.pm'};
506     require C4::Auth_with_ldap;
507     C4::Auth_with_ldap->import;
508     return;
509 }
510
511 sub is_admin_bind {
512     my @args = @_;
513
514     if ($#args <= 1 || $args[1] eq 'cn=Manager,dc=metavore,dc=com') {
515         return 1;
516     }
517
518     return 0;
519 }
520
521 $schema->storage->txn_rollback();
522