Bug 17615 - Fix updating borrower attributes in checkpw_ldap
[koha-ffzg.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::TestBuilder;
24 use Test::Warn;
25
26 use C4::Context;
27
28 use Koha::Patrons;
29
30 my $dbh = '';
31
32 # Start transaction
33 my $database = Koha::Database->new();
34 my $schema = $database->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_bind_result           = 'error';
49 my $desired_compare_result        = 'error';
50 my $desired_search_result         = 'error';
51 my $desired_count_result          = 1;
52 my $non_anonymous_bind_result     = 'error';
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_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_bind_result           = 'success';
167         $desired_search_result         = 'success';
168         $desired_count_result          = 1;
169         $non_anonymous_bind_result     = 'success';
170         $update                        = 1;
171         reload_ldap_module();
172
173         my $auth = Test::MockModule->new('C4::Auth_with_ldap');
174         $auth->mock(
175             'update_local',
176             sub {
177                 return $borrower->{cardnumber};
178             }
179         );
180         $auth->mock(
181             'ldap_entry_2_hash',
182             sub {
183                 return (
184                     $attr_type2->{code}, 'BAR'
185                 );
186             }
187         );
188
189         C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' );
190         ok(
191             @{
192                 C4::Members::Attributes::GetBorrowerAttributes(
193                     $borrower->{borrowernumber}
194                 )
195             },
196             'Extended attributes are not deleted'
197         );
198
199         is( C4::Members::Attributes::GetBorrowerAttributeValue($borrower->{borrowernumber}, $attr_type2->{code}), 'BAR', 'Mapped attribute is BAR' );
200         $auth->unmock('update_local');
201         $auth->unmock('ldap_entry_2_hash');
202
203         $update               = 0;
204         $desired_count_result = 0;    # user auth problem
205         Koha::Patrons->find( $borrower->{borrowernumber} )->delete;
206         reload_ldap_module();
207         is(
208             C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' ),
209             0,
210             'checkpw_ldap returns 0 if user lookup returns 0'
211         );
212
213         $non_anonymous_bind_result = 'error';
214         reload_ldap_module();
215
216         warning_like {
217             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
218                 password => 'hey' );
219         }
220         qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
221           'checkpw_ldap prints correct warning if LDAP bind fails';
222         is( $ret, -1,
223             'checkpw_ldap returns -1 LDAP bind fails for user (Bug 8148)' );
224
225         # regression tests for bug 12831
226         $desired_authentication_result = 'error';
227         $anonymous_bind                = 0;
228         $desired_bind_result           = 'error';
229         $desired_search_result         = 'success';
230         $desired_count_result          = 0;           # user auth problem
231         $non_anonymous_bind_result     = 'error';
232         reload_ldap_module();
233
234         warning_like {
235             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
236                 password => 'hey' );
237         }
238         qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
239           'checkpw_ldap prints correct warning if LDAP bind fails';
240         is( $ret, 0,
241             'checkpw_ldap returns 0 LDAP bind fails for user (Bug 12831)' );
242
243     };
244
245     subtest 'auth_by_bind = 0 tests' => sub {
246
247         plan tests => 8;
248
249         $auth_by_bind = 0;
250
251         # Anonymous bind
252         $anonymous_bind            = 1;
253         $desired_bind_result       = 'error';
254         $non_anonymous_bind_result = 'error';
255         reload_ldap_module();
256
257         warning_like {
258             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
259                 password => 'hey' );
260         }
261 qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
262           'checkpw_ldap prints correct warning if LDAP bind fails';
263         is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' );
264
265         $anonymous_bind            = 1;
266         $desired_bind_result       = 'success';
267         $non_anonymous_bind_result = 'success';
268         $desired_compare_result    = 'error';
269         reload_ldap_module();
270
271         warning_like {
272             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
273                 password => 'hey' );
274         }
275 qr/LDAP Auth rejected : invalid password for user 'hola'. LDAP error #1: error_name/,
276           'checkpw_ldap prints correct warning if LDAP bind fails';
277         is( $ret, -1, 'checkpw_ldap returns -1 if bind fails (Bug 8148)' );
278
279         # Non-anonymous bind
280         $anonymous_bind            = 0;
281         $desired_bind_result       = 'success';
282         $non_anonymous_bind_result = 'error';
283         $desired_compare_result    = 'dont care';
284         reload_ldap_module();
285
286         warning_like {
287             $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola',
288                 password => 'hey' );
289         }
290 qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
291           'checkpw_ldap prints correct warning if LDAP bind fails';
292         is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' );
293
294         $anonymous_bind            = 0;
295         $desired_bind_result       = 'success';
296         $non_anonymous_bind_result = 'success';
297         $desired_compare_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'. LDAP error #1: error_name/,
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 => 5;
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     $desired_search_result = 'success';
335     $desired_count_result  = 2;
336     reload_ldap_module();
337     warning_like { $ret = C4::Auth_with_ldap::search_method( $ldap, '123' ) }
338     qr/^LDAP Auth rejected \: \(uid\=123\) gets 2 hits/,
339       'search_method prints correct warning when hits count is not 1';
340     is( $ret, 0, 'search_method returns 0 when hits count is not 1' );
341
342 };
343
344 # Function that mocks the call to C4::Context->config(param)
345 sub mockedC4Config {
346     my $class = shift;
347     my $param = shift;
348
349     if ( $param eq 'useshibboleth' ) {
350         return 0;
351     }
352     if ( $param eq 'ldapserver' ) {
353         my %ldap_mapping = (
354             firstname    => { is => 'givenname' },
355             surname      => { is => 'sn' },
356             address      => { is => 'postaladdress' },
357             city         => { is => 'l' },
358             zipcode      => { is => 'postalcode' },
359             branchcode   => { is => 'branch' },
360             userid       => { is => 'uid' },
361             password     => { is => 'userpassword' },
362             email        => { is => 'mail' },
363             categorycode => { is => 'employeetype' },
364             phone        => { is => 'telephonenumber' },
365         );
366
367         my %ldap_config = (
368             anonymous_bind => $anonymous_bind,
369             auth_by_bind   => $auth_by_bind,
370             base           => 'dc=metavore,dc=com',
371             hostname       => 'localhost',
372             mapping        => \%ldap_mapping,
373             pass           => 'metavore',
374             principal_name => '%s@my_domain.com',
375             replicate      => $replicate,
376             update         => $update,
377             user           => 'cn=Manager,dc=metavore,dc=com',
378         );
379         return \%ldap_config;
380     }
381     if ( $param =~ /(intranetdir|opachtdocs|intrahtdocs)/x ) {
382         return q{};
383     }
384     if ( ref $class eq 'HASH' ) {
385         return $class->{$param};
386     }
387     return;
388 }
389
390 # Function that mocks the call to Net::LDAP
391 sub mock_net_ldap {
392
393     my $mocked_ldap = Test::MockObject->new();
394
395     $mocked_ldap->mock(
396         'bind',
397         sub {
398
399             my @args = @_;
400             my $mocked_message;
401
402             if ( $#args > 1 ) {
403
404                 # Args passed => non-anonymous bind
405                 if ( $non_anonymous_bind_result eq 'error' ) {
406                     return mock_net_ldap_message( 1, 1, 'error_name',
407                         'error_text' );
408                 }
409                 else {
410                     return mock_net_ldap_message( 0, 0, q{}, q{} );
411                 }
412             }
413             else {
414                 $mocked_message = mock_net_ldap_message(
415                     ( $desired_bind_result eq 'error' ) ? 1 : 0,    # code
416                     ( $desired_bind_result eq 'error' ) ? 1 : 0,    # error
417                     ( $desired_bind_result eq 'error' )
418                     ? 'error_name'
419                     : 0,                                            # error_name
420                     ( $desired_bind_result eq 'error' )
421                     ? 'error_text'
422                     : 0                                             # error_text
423                 );
424             }
425
426             return $mocked_message;
427         }
428     );
429
430     $mocked_ldap->mock(
431         'compare',
432         sub {
433
434             my $mocked_message;
435
436             if ( $desired_compare_result eq 'error' ) {
437                 $mocked_message =
438                   mock_net_ldap_message( 1, 1, 'error_name', 'error_text' );
439             }
440             else {
441                 # we expect return code 6 for success
442                 $mocked_message = mock_net_ldap_message( 6, 0, q{}, q{} );
443             }
444
445             return $mocked_message;
446         }
447     );
448
449     $mocked_ldap->mock(
450         'search',
451         sub {
452
453             return mock_net_ldap_search(
454                 {
455                     count => ($desired_count_result)
456                     ? $desired_count_result
457                     : 1,    # default to 1
458                     code => ( $desired_search_result eq 'error' )
459                     ? 1
460                     : 0,    # 0 == success
461                     error => ( $desired_search_result eq 'error' ) ? 1
462                     : 0,
463                     error_text => ( $desired_search_result eq 'error' )
464                     ? 'error_text'
465                     : undef,
466                     error_name => ( $desired_search_result eq 'error' )
467                     ? 'error_name'
468                     : undef,
469                     shift_entry => mock_net_ldap_entry( 'sampledn', 1 )
470                 }
471             );
472
473         }
474     );
475
476     return $mocked_ldap;
477 }
478
479 sub mock_net_ldap_search {
480     my ($parameters) = @_;
481
482     my $count       = $parameters->{count};
483     my $code        = $parameters->{code};
484     my $error       = $parameters->{error};
485     my $error_text  = $parameters->{error_text};
486     my $error_name  = $parameters->{error_name};
487     my $shift_entry = $parameters->{shift_entry};
488
489     my $mocked_search = Test::MockObject->new();
490     $mocked_search->mock( 'count',       sub { return $count; } );
491     $mocked_search->mock( 'code',        sub { return $code; } );
492     $mocked_search->mock( 'error',       sub { return $error; } );
493     $mocked_search->mock( 'error_name',  sub { return $error_name; } );
494     $mocked_search->mock( 'error_text',  sub { return $error_text; } );
495     $mocked_search->mock( 'shift_entry', sub { return $shift_entry; } );
496
497     return $mocked_search;
498 }
499
500 sub mock_net_ldap_message {
501     my ( $code, $error, $error_name, $error_text ) = @_;
502
503     my $mocked_message = Test::MockObject->new();
504     $mocked_message->mock( 'code',       sub { $code } );
505     $mocked_message->mock( 'error',      sub { $error } );
506     $mocked_message->mock( 'error_name', sub { $error_name } );
507     $mocked_message->mock( 'error_text', sub { $error_text } );
508
509     return $mocked_message;
510 }
511
512 sub mock_net_ldap_entry {
513     my ( $dn, $exists ) = @_;
514
515     my $mocked_entry = Test::MockObject->new();
516     $mocked_entry->mock( 'dn',     sub { return $dn; } );
517     $mocked_entry->mock( 'exists', sub { return $exists } );
518
519     return $mocked_entry;
520 }
521
522 # TODO: Once we remove the global variables in C4::Auth_with_ldap
523 # we shouldn't need this...
524 # ... Horrible hack
525 sub reload_ldap_module {
526     delete $INC{'C4/Auth_with_ldap.pm'};
527     require C4::Auth_with_ldap;
528     C4::Auth_with_ldap->import;
529     return;
530 }
531
532 $schema->storage->txn_rollback();
533
534 1;