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