001f2a8c277f7141a322c4d1d515039df1a479c9
[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             Koha::Patrons->find($borrower->{borrowernumber})->get_extended_attributes->count,
210             'Extended attributes are not deleted'
211         );
212
213         is( $patron->get_extended_attribute( $attr_type2->{code} )->attribute, 'BAR', 'Mapped attribute is BAR' );
214         $auth->unmock('update_local');
215         $auth->unmock('ldap_entry_2_hash');
216
217         $update               = 0;
218         $desired_count_result = 0;    # user auth problem
219         $patron->delete;
220         reload_ldap_module();
221         is(
222             C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' ),
223             0,
224             'checkpw_ldap returns 0 if user lookup returns 0'
225         );
226
227         $desired_bind_result = 'error';
228         reload_ldap_module();
229
230         warning_like {
231             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
232                 password => 'hey' );
233         }
234         qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
235           'checkpw_ldap prints correct warning if LDAP bind fails';
236         is( $ret, -1,
237             'checkpw_ldap returns -1 LDAP bind fails for user (Bug 8148)' );
238
239         # regression tests for bug 12831
240         $desired_authentication_result = 'error';
241         $anonymous_bind                = 0;
242         $desired_admin_bind_result   = 'error';
243         $desired_search_result         = 'success';
244         $desired_count_result          = 0;           # user auth problem
245         $desired_bind_result = 'error';
246         reload_ldap_module();
247
248         warning_like {
249             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
250                 password => 'hey' );
251         }
252         qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
253           'checkpw_ldap prints correct warning if LDAP bind fails';
254         is( $ret, 0,
255             'checkpw_ldap returns 0 LDAP bind fails for user (Bug 12831)' );
256
257     };
258
259     subtest 'auth_by_bind = 0 tests' => sub {
260
261         plan tests => 8;
262
263         $auth_by_bind = 0;
264
265         # Anonymous bind
266         $anonymous_bind            = 1;
267         $user                      = 'cn=Manager,dc=metavore,dc=com';
268         $pass                      = 'metavore';
269         $desired_admin_bind_result = 'error';
270         $desired_bind_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 bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
278           'checkpw_ldap prints correct warning if LDAP bind fails';
279         is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' );
280
281         $anonymous_bind            = 1;
282         $desired_admin_bind_result = 'success';
283         $desired_bind_result = 'error';
284         $desired_search_result = 'success';
285         $desired_count_result = 1;
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 Auth rejected : invalid password for user 'hola'./,
293           'checkpw_ldap prints correct warning if LDAP bind fails';
294         is( $ret, -1, 'checkpw_ldap returns -1 if bind fails (Bug 8148)' );
295
296         # Non-anonymous bind
297         $anonymous_bind            = 0;
298         $desired_admin_bind_result = 'error';
299         $desired_bind_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 bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
307           'checkpw_ldap prints correct warning if LDAP bind fails';
308         is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' );
309
310         $anonymous_bind            = 0;
311         $desired_admin_bind_result = 'success';
312         $desired_bind_result = 'error';
313         reload_ldap_module();
314
315         warning_like {
316             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
317                 password => 'hey' );
318         }
319 qr/LDAP Auth rejected : invalid password for user 'hola'./,
320           'checkpw_ldap prints correct warning if LDAP bind fails';
321         is( $ret, -1, 'checkpw_ldap returns -1 if bind fails (Bug 8148)' );
322
323     };
324 };
325
326 subtest 'search_method tests' => sub {
327
328     plan tests => 3;
329
330     my $ldap = mock_net_ldap();
331
332     # Null params tests
333     is( C4::Auth_with_ldap::search_method( $ldap, undef ),
334         undef, 'search_method returns undef on undefined userid' );
335     is( C4::Auth_with_ldap::search_method( undef, 'undef' ),
336         undef, 'search_method returns undef on undefined ldap object' );
337
338     # search ->code and !->code
339     $desired_search_result = 'error';
340     reload_ldap_module();
341     my $eval_retval =
342       eval { $ret = C4::Auth_with_ldap::search_method( $ldap, 'undef' ); };
343     like(
344         $@,
345         qr/LDAP search failed to return object : 1/,
346 'search_method prints correct warning when db->search returns error code'
347     );
348 };
349
350 # Function that mocks the call to C4::Context->config(param)
351 sub mockedC4Config {
352     my $class = shift;
353     my $param = shift;
354
355     if ( $param eq 'useshibboleth' ) {
356         return 0;
357     }
358     if ( $param eq 'ldapserver' ) {
359         my %ldap_mapping = (
360             firstname    => { is => 'givenname' },
361             surname      => { is => 'sn' },
362             address      => { is => 'postaladdress' },
363             city         => { is => 'l' },
364             zipcode      => { is => 'postalcode' },
365             branchcode   => { is => 'branch' },
366             userid       => { is => 'uid' },
367             password     => { is => 'userpassword' },
368             email        => { is => 'mail' },
369             categorycode => { is => 'employeetype' },
370             phone        => { is => 'telephonenumber' },
371         );
372
373         my %ldap_config = (
374             anonymous_bind => $anonymous_bind,
375             auth_by_bind   => $auth_by_bind,
376             base           => 'dc=metavore,dc=com',
377             hostname       => 'localhost',
378             mapping        => \%ldap_mapping,
379             pass           => $pass,
380             principal_name => '%s@my_domain.com',
381             replicate      => $replicate,
382             update         => $update,
383             user           => $user,
384         );
385         return \%ldap_config;
386     }
387     if ( $param =~ /(intranetdir|opachtdocs|intrahtdocs)/x ) {
388         return q{};
389     }
390     if ( ref $class eq 'HASH' ) {
391         return $class->{$param};
392     }
393     return;
394 }
395
396 # Function that mocks the call to Net::LDAP
397 sub mock_net_ldap {
398
399     my $mocked_ldap = Test::MockObject->new();
400
401     $mocked_ldap->mock( 'bind', sub {
402         if (is_admin_bind(@_)) {
403             return mock_net_ldap_message(
404                 ($desired_admin_bind_result eq 'error' ) ? 1 : 0, # code
405                 ($desired_admin_bind_result eq 'error' ) ? 1 : 0, # error
406                 ($desired_admin_bind_result eq 'error' ) ? 'error_name' : 0, # error_name
407                 ($desired_admin_bind_result eq 'error' ) ? 'error_text' : 0  # error_text
408             );
409         }
410         else {
411             if ( $desired_bind_result eq 'error' ) {
412                 return mock_net_ldap_message(1,1,'error_name','error_text');
413             }
414             return mock_net_ldap_message(0,0,'','');
415         }
416     });
417
418     $mocked_ldap->mock(
419         'search',
420         sub {
421
422             $remaining_entry = 1;
423
424             return mock_net_ldap_search(
425                 {
426                     count => ($desired_count_result)
427                     ? $desired_count_result
428                     : 1,    # default to 1
429                     code => ( $desired_search_result eq 'error' )
430                     ? 1
431                     : 0,    # 0 == success
432                     error => ( $desired_search_result eq 'error' ) ? 1
433                     : 0,
434                     error_text => ( $desired_search_result eq 'error' )
435                     ? 'error_text'
436                     : undef,
437                     error_name => ( $desired_search_result eq 'error' )
438                     ? 'error_name'
439                     : undef,
440                     shift_entry => mock_net_ldap_entry( 'sampledn', 1 )
441                 }
442             );
443
444         }
445     );
446
447     return $mocked_ldap;
448 }
449
450 sub mock_net_ldap_search {
451     my ($parameters) = @_;
452
453     my $count       = $parameters->{count};
454     my $code        = $parameters->{code};
455     my $error       = $parameters->{error};
456     my $error_text  = $parameters->{error_text};
457     my $error_name  = $parameters->{error_name};
458     my $shift_entry = $parameters->{shift_entry};
459
460     my $mocked_search = Test::MockObject->new();
461     $mocked_search->mock( 'count',       sub { return $count; } );
462     $mocked_search->mock( 'code',        sub { return $code; } );
463     $mocked_search->mock( 'error',       sub { return $error; } );
464     $mocked_search->mock( 'error_name',  sub { return $error_name; } );
465     $mocked_search->mock( 'error_text',  sub { return $error_text; } );
466     $mocked_search->mock( 'shift_entry', sub {
467         if ($remaining_entry) {
468             $remaining_entry--;
469             return $shift_entry;
470         }
471         return '';
472     });
473
474     return $mocked_search;
475 }
476
477 sub mock_net_ldap_message {
478     my ( $code, $error, $error_name, $error_text ) = @_;
479
480     my $mocked_message = Test::MockObject->new();
481     $mocked_message->mock( 'code',       sub { $code } );
482     $mocked_message->mock( 'error',      sub { $error } );
483     $mocked_message->mock( 'error_name', sub { $error_name } );
484     $mocked_message->mock( 'error_text', sub { $error_text } );
485
486     return $mocked_message;
487 }
488
489 sub mock_net_ldap_entry {
490     my ( $dn, $exists ) = @_;
491
492     my $mocked_entry = Test::MockObject->new();
493     $mocked_entry->mock( 'dn',     sub { return $dn; } );
494     $mocked_entry->mock( 'exists', sub { return $exists } );
495
496     return $mocked_entry;
497 }
498
499 # TODO: Once we remove the global variables in C4::Auth_with_ldap
500 # we shouldn't need this...
501 # ... Horrible hack
502 sub reload_ldap_module {
503     delete $INC{'C4/Auth_with_ldap.pm'};
504     require C4::Auth_with_ldap;
505     C4::Auth_with_ldap->import;
506     return;
507 }
508
509 sub is_admin_bind {
510     my @args = @_;
511
512     if ($#args <= 1 || $args[1] eq 'cn=Manager,dc=metavore,dc=com') {
513         return 1;
514     }
515
516     return 0;
517 }
518
519 $schema->storage->txn_rollback();
520